diff options
Diffstat (limited to 'actionpack')
144 files changed, 2115 insertions, 1609 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 74a8d9f78a..a4f5116a5d 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,8 +1,27 @@ ## Rails 4.0.0 (unreleased) ## -* Forms of persisted records use always PATCH (via the `_method` hack). *fxn* +* Remove the leading \n added by textarea on assert_select. *Santiago Pastorino* -* For resources, both PATCH and PUT are routed to the `update` action. *fxn* +* Changed default value for `config.action_view.embed_authenticity_token_in_remote_forms` + to `false`. This change breaks remote forms that need to work also without javascript, + so if you need such behavior, you can either set it to `true` or explicitly pass + `:authenticity_token => true` in form options + +* Added ActionDispatch::SSL middleware that when included force all the requests to be under HTTPS protocol. *Rafael Mendonça França* + +* Add `include_hidden` option to select tag. With `:include_hidden => false` select with `multiple` attribute doesn't generate hidden input with blank value. *Vasiliy Ermolovich* + +* Removed default `size` option from the `text_field`, `search_field`, `telephone_field`, `url_field`, `email_field` helpers. *Philip Arndt* + +* Removed default `cols` and `rows` options from the `text_area` helper. *Philip Arndt* + +* Adds support for layouts when rendering a partial with a given collection. *serabe* + +* Allows the route helper `root` to take a string argument. For example, `root 'pages#main'`. *bcardarella* + +* Forms of persisted records use always PATCH (via the `_method` hack). *fxn* + +* For resources, both PATCH and PUT are routed to the `update` action. *fxn* * Don't ignore `force_ssl` in development. This is a change of behavior - use a `:if` condition to recreate the old behavior. @@ -79,6 +98,9 @@ * check_box with `:form` html5 attribute will now replicate the `:form` attribute to the hidden field as well. *Carlos Antonio da Silva* +* Turn off verbose mode of rack-cache, we still have X-Rack-Cache to + check that info. Closes #5245. *Santiago Pastorino* + * `label` form helper accepts :for => nil to not generate the attribute. *Carlos Antonio da Silva* * Add `:format` option to number_to_percentage *Rodrigo Flores* @@ -107,11 +129,30 @@ * `favicon_link_tag` helper will now use the favicon in app/assets by default. *Lucas Caton* -* `ActionView::Helpers::TextHelper#highlight` now defaults to the - HTML5 `mark` element. *Brian Cardarella* +* `ActionView::Helpers::TextHelper#highlight` now defaults to the + HTML5 `mark` element. *Brian Cardarella* + + +## Rails 3.2.3 (unreleased) ## + +* Add `config.action_view.embed_authenticity_token_in_remote_forms` (defaults to true) which allows to set if authenticity token will be included by default in remote forms. If you change it to false, you can still force authenticity token by passing `:authenticity_token => true` in form options *Piotr Sarnacki* +* Do not include the authenticity token in forms where remote: true as ajax forms use the meta-tag value *DHH* -## Rails 3.2.2 (unreleased) ## +* Upgrade rack-cache to 1.2. *José Valim* + +* ActionController::SessionManagement is removed. *Santiago Pastorino* + +* Since the router holds references to many parts of the system like engines, controllers and the application itself, inspecting the route set can actually be really slow, therefore we default alias inspect to to_s. *José Valim* + +* Add a new line after the textarea opening tag. Closes #393 *Rafael Mendonça França* + +* Always pass a respond block from to responder. We should let the responder decide what to do with the given overridden response block, and not short circuit it. *Prem Sichanugrist* + +* Fixes layout rendering regression from 3.2.2. *José Valim* + + +## Rails 3.2.2 (March 1, 2012) ## * Format lookup for partials is derived from the format in which the template is being rendered. Closes #5025 part 2 *Santiago Pastorino* @@ -301,7 +342,8 @@ returned by the class method attribute_names will be wrapped. This fixes the wrapping of nested attributes by adding them to attr_accessible. -## Rails 3.1.4 (unreleased) ## + +## Rails 3.1.4 (March 1, 2012) ## * Skip assets group in Gemfile and all assets configurations options when the application is generated with --skip-sprockets option. @@ -317,6 +359,7 @@ * Assets should use the request protocol by default or default to relative if no request is available *Jonathan del Strother* + ## Rails 3.1.3 (November 20, 2011) ## * Downgrade sprockets to ~> 2.0.3. Using 2.1.0 caused regressions. @@ -326,6 +369,7 @@ *Jon Leighton* + ## Rails 3.1.2 (November 18, 2011) ## * Fix XSS security vulnerability in the `translate` helper method. When using interpolation @@ -367,6 +411,7 @@ * Ensure users upgrading from 3.0.x to 3.1.x will properly upgrade their flash object in session (issues #3298 and #2509) + ## Rails 3.1.1 (October 07, 2011) ## * javascript_path and stylesheet_path now refer to /assets if asset pipelining @@ -603,7 +648,7 @@ * Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. *Yehuda Katz, Carl Lerche* -## Rails 3.0.12 (unreleased) ## +## Rails 3.0.12 (March 1, 2012) ## * Fix using `tranlate` helper with a html translation which uses the `:count` option for pluralization. diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index b205acdb79..589a67dc02 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -18,12 +18,11 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('activemodel', version) - s.add_dependency('rack-cache', '~> 1.1') + s.add_dependency('rack-cache', '~> 1.2') s.add_dependency('builder', '~> 3.0.0') s.add_dependency('rack', '~> 1.4.1') s.add_dependency('rack-test', '~> 0.6.1') s.add_dependency('journey', '~> 1.0.1') - s.add_dependency('sprockets', '~> 2.2.0') s.add_dependency('erubis', '~> 2.7.0') s.add_development_dependency('tzinfo', '~> 0.3.29') diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb index 43cea3b79e..b068846a13 100644 --- a/actionpack/lib/abstract_controller/base.rb +++ b/actionpack/lib/abstract_controller/base.rb @@ -1,4 +1,5 @@ require 'erubis' +require 'set' require 'active_support/configurable' require 'active_support/descendants_tracker' require 'active_support/core_ext/module/anonymous' @@ -59,7 +60,7 @@ module AbstractController # itself. Finally, #hidden_actions are removed. # # ==== Returns - # * <tt>array</tt> - A list of all methods that should be considered actions. + # * <tt>set</tt> - A set of all methods that should be considered actions. def action_methods @action_methods ||= begin # All public instance methods of this class, including ancestors @@ -72,7 +73,7 @@ module AbstractController hidden_actions.to_a # Clear out AS callback method pollution - methods.reject { |method| method =~ /_one_time_conditions/ } + Set.new(methods.reject { |method| method =~ /_one_time_conditions/ }) end end diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index aa39e21ba9..bc9f6fc3e8 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -89,7 +89,7 @@ module AbstractController # class TillController < BankController # layout false # - # In these examples, we have three implicit lookup scenrios: + # In these examples, we have three implicit lookup scenarios: # * The BankController uses the "bank" layout. # * The ExchangeController uses the "exchange" layout. # * The CurrencyController inherits the layout from BankController. @@ -120,6 +120,7 @@ module AbstractController # def writers_and_readers # logged_in? ? "writer_layout" : "reader_layout" # end + # end # # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing # is logged in or not. @@ -127,7 +128,14 @@ module AbstractController # If you want to use an inline method, such as a proc, do something like this: # # class WeblogController < ActionController::Base - # layout proc{ |controller| controller.logged_in? ? "writer_layout" : "reader_layout" } + # layout proc { |controller| controller.logged_in? ? "writer_layout" : "reader_layout" } + # end + # + # If an argument isn't given to the proc, it's evaluated in the context of + # the current controller anyway. + # + # class WeblogController < ActionController::Base + # layout proc { logged_in? ? "writer_layout" : "reader_layout" } # end # # Of course, the most common way of specifying a layout is still just as a plain template name: @@ -136,8 +144,8 @@ module AbstractController # layout "weblog_standard" # end # - # If no directory is specified for the template name, the template will by default be looked for in <tt>app/views/layouts/</tt>. - # Otherwise, it will be looked up relative to the template root. + # The template will be looked always in <tt>app/views/layouts/</tt> folder. But you can point + # <tt>layouts</tt> folder direct also. <tt>layout "layouts/demo"</tt> is the same as <tt>layout "demo"</tt>. # # Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists. # Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent: @@ -238,10 +246,10 @@ module AbstractController # # If the specified layout is a: # String:: the String is the template name - # Symbol:: call the method specified by the symbol, which will return - # the template name + # Symbol:: call the method specified by the symbol, which will return the template name # false:: There is no layout # true:: raise an ArgumentError + # nil:: Force default layout behavior with inheritance # # ==== Parameters # * <tt>layout</tt> - The layout to use. @@ -280,6 +288,10 @@ module AbstractController <<-RUBY lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first || super RUBY + else + <<-RUBY + super + RUBY end layout_definition = case _layout @@ -295,12 +307,12 @@ module AbstractController end RUBY when Proc - define_method :_layout_from_proc, &_layout - "_layout_from_proc(self)" + define_method :_layout_from_proc, &_layout + _layout.arity == 0 ? "_layout_from_proc" : "_layout_from_proc(self)" when false nil when true - raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil" + raise ArgumentError, "Layouts must be specified as a String, Symbol, Proc, false, or nil" when nil name_clause end @@ -360,7 +372,7 @@ module AbstractController when false, nil then nil else raise ArgumentError, - "String, true, or false, expected for `layout'; you passed #{name.inspect}" + "String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}" end end diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index ddc93464cd..7d73c6af8d 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -105,6 +105,7 @@ module AbstractController # Find and renders a template based on the options given. # :api: private def _render_template(options) #:nodoc: + lookup_context.rendered_format = nil if options[:formats] view_renderer.render(view_context, options) end diff --git a/actionpack/lib/abstract_controller/url_for.rb b/actionpack/lib/abstract_controller/url_for.rb index e4261068d8..4a95e1f276 100644 --- a/actionpack/lib/abstract_controller/url_for.rb +++ b/actionpack/lib/abstract_controller/url_for.rb @@ -1,10 +1,10 @@ -# Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class -# has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an -# exception will be raised. -# -# Note that this module is completely decoupled from HTTP - the only requirement is a valid -# <tt>_routes</tt> implementation. module AbstractController + # Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class + # has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an + # exception will be raised. + # + # Note that this module is completely decoupled from HTTP - the only requirement is a valid + # <tt>_routes</tt> implementation. module UrlFor extend ActiveSupport::Concern include ActionDispatch::Routing::UrlFor diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb index a0c54dbd84..7c10fcbb8a 100644 --- a/actionpack/lib/action_controller.rb +++ b/actionpack/lib/action_controller.rb @@ -31,7 +31,6 @@ module ActionController autoload :RequestForgeryProtection autoload :Rescue autoload :Responder - autoload :SessionManagement autoload :Streaming autoload :Testing autoload :UrlFor diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 3b82231b15..71425cd542 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -171,6 +171,16 @@ module ActionController class Base < Metal abstract! + # Shortcut helper that returns all the ActionController::Base modules except the ones passed in the argument: + # + # class MetalController + # ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left| + # include left + # end + # end + # + # This gives better control over what you want to exclude and makes it easier + # to create a bare controller class, instead of listing the modules required manually. def self.without_modules(*modules) modules = modules.map do |m| m.is_a?(Symbol) ? ActionController.const_get(m) : m @@ -192,7 +202,6 @@ module ActionController Renderers::All, ConditionalGet, RackDelegation, - SessionManagement, Caching, MimeResponds, ImplicitRender, diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb index ba96735e56..59ec197347 100644 --- a/actionpack/lib/action_controller/caching/actions.rb +++ b/actionpack/lib/action_controller/caching/actions.rb @@ -40,7 +40,7 @@ module ActionController #:nodoc: # # You can modify the default action cache path by passing a # <tt>:cache_path</tt> option. This will be passed directly to - # <tt>ActionCachePath.path_for</tt>. This is handy for actions with + # <tt>ActionCachePath.new</tt>. This is handy for actions with # multiple possible routes that should be cached differently. If a # block is given, it is called with the current controller instance. # @@ -170,14 +170,14 @@ module ActionController #:nodoc: options.reverse_merge!(:format => @extension) if options.is_a?(Hash) end - path = controller.url_for(options).split(%r{://}).last + path = controller.url_for(options).split('://', 2).last @path = normalize!(path) end private def normalize!(path) path << 'index' if path[-1] == ?/ - path << ".#{extension}" if extension and !path.split('?').first.ends_with?(".#{extension}") + path << ".#{extension}" if extension and !path.split('?', 2).first.ends_with?(".#{extension}") 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 159f718029..307594d54a 100644 --- a/actionpack/lib/action_controller/caching/pages.rb +++ b/actionpack/lib/action_controller/caching/pages.rb @@ -99,7 +99,7 @@ module ActionController #:nodoc: # caches_page :index # # # cache the index action except for JSON requests - # caches_page :index, :if => Proc.new { |c| !c.request.format.json? } + # caches_page :index, :if => Proc.new { !request.format.json? } # # # don't gzip images # caches_page :image, :gzip => false diff --git a/actionpack/lib/action_controller/caching/sweeping.rb b/actionpack/lib/action_controller/caching/sweeping.rb index 49cf70ec21..bb176ca3f9 100644 --- a/actionpack/lib/action_controller/caching/sweeping.rb +++ b/actionpack/lib/action_controller/caching/sweeping.rb @@ -54,6 +54,11 @@ module ActionController #:nodoc: class Sweeper < ActiveRecord::Observer #:nodoc: attr_accessor :controller + def initialize(*args) + super + @controller = nil + end + def before(controller) self.controller = controller callback(:before) if controller.perform_caching @@ -88,7 +93,7 @@ module ActionController #:nodoc: end def method_missing(method, *arguments, &block) - return unless @controller + super unless @controller @controller.__send__(method, *arguments, &block) end end diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb index 2a8e4c575e..5b25a0d303 100644 --- a/actionpack/lib/action_controller/metal/conditional_get.rb +++ b/actionpack/lib/action_controller/metal/conditional_get.rb @@ -110,8 +110,8 @@ module ActionController # # Examples: # expires_in 20.minutes + # expires_in 3.hours, :public => true # expires_in 3.hours, :public => true, :must_revalidate => true - # expires_in 3.hours, 'max-stale' => 5.hours, :public => true # # This method will overwrite an existing Cache-Control header. # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities. diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb index ece9ba3725..9a9db0fe5f 100644 --- a/actionpack/lib/action_controller/metal/exceptions.rb +++ b/actionpack/lib/action_controller/metal/exceptions.rb @@ -14,8 +14,6 @@ module ActionController end class MethodNotAllowed < ActionControllerError #:nodoc: - attr_reader :allowed_methods - def initialize(*allowed_methods) super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.") end @@ -30,9 +28,6 @@ module ActionController class MissingFile < ActionControllerError #:nodoc: end - class RenderError < ActionControllerError #:nodoc: - end - class SessionOverflowError < ActionControllerError #:nodoc: DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.' diff --git a/actionpack/lib/action_controller/metal/force_ssl.rb b/actionpack/lib/action_controller/metal/force_ssl.rb index a1e40fc4e0..ac12cbb625 100644 --- a/actionpack/lib/action_controller/metal/force_ssl.rb +++ b/actionpack/lib/action_controller/metal/force_ssl.rb @@ -44,7 +44,7 @@ module ActionController redirect_options = {:protocol => 'https://', :status => :moved_permanently} redirect_options.merge!(:host => host) if host redirect_options.merge!(:params => request.query_parameters) - flash.keep + flash.keep if respond_to?(:flash) redirect_to redirect_options end end diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb index d070eaae5d..1a4bca12d2 100644 --- a/actionpack/lib/action_controller/metal/helpers.rb +++ b/actionpack/lib/action_controller/metal/helpers.rb @@ -52,6 +52,7 @@ module ActionController module Helpers extend ActiveSupport::Concern + class << self; attr_accessor :helpers_path; end include AbstractController::Helpers included do diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb index b8b43ea9ef..44d2f740e6 100644 --- a/actionpack/lib/action_controller/metal/http_authentication.rb +++ b/actionpack/lib/action_controller/metal/http_authentication.rb @@ -263,7 +263,7 @@ module ActionController # The quality of the implementation depends on a good choice. # A nonce might, for example, be constructed as the base 64 encoding of # - # => time-stamp H(time-stamp ":" ETag ":" private-key) + # time-stamp H(time-stamp ":" ETag ":" private-key) # # where time-stamp is a server-generated time or other non-repeating value, # ETag is the value of the HTTP ETag header associated with the requested entity, diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb index 55de7e7d8e..f467b74256 100644 --- a/actionpack/lib/action_controller/metal/mime_responds.rb +++ b/actionpack/lib/action_controller/metal/mime_responds.rb @@ -6,8 +6,6 @@ module ActionController #:nodoc: module MimeResponds extend ActiveSupport::Concern - include ActionController::ImplicitRender - included do class_attribute :responder, :mimes_for_respond_to self.responder = ActionController::Responder @@ -58,7 +56,7 @@ module ActionController #:nodoc: # Clear all mime types in <tt>respond_to</tt>. # def clear_respond_to - self.mimes_for_respond_to = ActiveSupport::OrderedHash.new.freeze + self.mimes_for_respond_to = Hash.new.freeze end end @@ -76,7 +74,7 @@ module ActionController #:nodoc: # # respond_to do |format| # format.html - # format.xml { render :xml => @people.to_xml } + # format.xml { render :xml => @people } # end # end # @@ -193,24 +191,110 @@ module ActionController #:nodoc: if collector = retrieve_collector_from_mimes(mimes, &block) response = collector.response - response ? response.call : default_render({}) + response ? response.call : render({}) end end - # respond_with wraps a resource around a responder for default representation. - # First it invokes respond_to, if a response cannot be found (ie. no block - # for the request was given and template was not available), it instantiates - # an ActionController::Responder with the controller and resource. + # For a given controller action, respond_with generates an appropriate + # response based on the mime-type requested by the client. # - # ==== Example + # If the method is called with just a resource, as in this example - # - # def index - # @users = User.all - # respond_with(@users) + # class PeopleController < ApplicationController + # respond_to :html, :xml, :json + # + # def index + # @people = Person.all + # respond_with @people + # end + # end + # + # then the mime-type of the response is typically selected based on the + # request's Accept header and the set of available formats declared + # by previous calls to the controller's class method +respond_to+. Alternatively + # the mime-type can be selected by explicitly setting <tt>request.format</tt> in + # the controller. + # + # If an acceptable format is not identified, the application returns a + # '406 - not acceptable' status. Otherwise, the default response is to render + # a template named after the current action and the selected format, + # e.g. <tt>index.html.erb</tt>. If no template is available, the behavior + # depends on the selected format: + # + # * for an html response - if the request method is +get+, an exception + # is raised but for other requests such as +post+ the response + # depends on whether the resource has any validation errors (i.e. + # assuming that an attempt has been made to save the resource, + # e.g. by a +create+ action) - + # 1. If there are no errors, i.e. the resource + # was saved successfully, the response +redirect+'s to the resource + # i.e. its +show+ action. + # 2. If there are validation errors, the response + # renders a default action, which is <tt>:new</tt> for a + # +post+ request or <tt>:edit</tt> for +put+. + # Thus an example like this - + # + # respond_to :html, :xml + # + # def create + # @user = User.new(params[:user]) + # flash[:notice] = 'User was successfully created.' if @user.save + # respond_with(@user) + # end + # + # is equivalent, in the absence of <tt>create.html.erb</tt>, to - + # + # def create + # @user = User.new(params[:user]) + # respond_to do |format| + # if @user.save + # flash[:notice] = 'User was successfully created.' + # format.html { redirect_to(@user) } + # format.xml { render :xml => @user } + # else + # format.html { render :action => "new" } + # format.xml { render :xml => @user } + # end + # end + # end + # + # * for a javascript request - if the template isn't found, an exception is + # raised. + # * for other requests - i.e. data formats such as xml, json, csv etc, if + # the resource passed to +respond_with+ responds to <code>to_<format></code>, + # the method attempts to render the resource in the requested format + # directly, e.g. for an xml request, the response is equivalent to calling + # <code>render :xml => resource</code>. + # + # === Nested resources + # + # As outlined above, the +resources+ argument passed to +respond_with+ + # can play two roles. It can be used to generate the redirect url + # for successful html requests (e.g. for +create+ actions when + # no template exists), while for formats other than html and javascript + # it is the object that gets rendered, by being converted directly to the + # required format (again assuming no template exists). + # + # For redirecting successful html requests, +respond_with+ also supports + # the use of nested resources, which are supplied in the same way as + # in <code>form_for</code> and <code>polymorphic_url</code>. For example - + # + # def create + # @project = Project.find(params[:project_id]) + # @task = @project.comments.build(params[:task]) + # flash[:notice] = 'Task was successfully created.' if @task.save + # respond_with(@project, @task) # end # - # It also accepts a block to be given. It's used to overwrite a default - # response: + # This would cause +respond_with+ to redirect to <code>project_task_url</code> + # instead of <code>task_url</code>. For request formats other than html or + # javascript, if multiple resources are passed in this way, it is the last + # one specified that is rendered. + # + # === Customizing response behavior + # + # Like +respond_to+, +respond_with+ may also be called with a block that + # can be used to overwrite any of the default responses, e.g. - # # def create # @user = User.new(params[:user]) @@ -221,13 +305,24 @@ module ActionController #:nodoc: # end # end # - # All options given to respond_with are sent to the underlying responder, - # except for the option :responder itself. Since the responder interface - # is quite simple (it just needs to respond to call), you can even give - # a proc to it. - # - # In order to use respond_with, first you need to declare the formats your - # controller responds to in the class level with a call to <tt>respond_to</tt>. + # The argument passed to the block is an ActionController::MimeResponds::Collector + # object which stores the responses for the formats defined within the + # block. Note that formats with responses defined explicitly in this way + # do not have to first be declared using the class method +respond_to+. + # + # Also, a hash passed to +respond_with+ immediately after the specified + # resource(s) is interpreted as a set of options relevant to all + # formats. Any option accepted by +render+ can be used, e.g. + # respond_with @people, :status => 200 + # However, note that these options are ignored after an unsuccessful attempt + # to save a resource, e.g. when automatically rendering <tt>:new</tt> + # after a post request. + # + # Two additional options are relevant specifically to +respond_with+ - + # 1. <tt>:location</tt> - overwrites the default redirect location used after + # a successful html +post+ request. + # 2. <tt>:action</tt> - overwrites the default render action used after an + # unsuccessful html +post+ request. # def respond_with(*resources, &block) raise "In order to use respond_with, first you need to declare the formats your " << @@ -235,16 +330,8 @@ module ActionController #:nodoc: if collector = retrieve_collector_from_mimes(&block) options = resources.size == 1 ? {} : resources.extract_options! - - if defined_response = collector.response - if action = options.delete(:action) - render :action => action - else - defined_response.call - end - else - (options.delete(:responder) || self.class.responder).call(self, resources, options) - end + options[:default_response] = collector.response + (options.delete(:responder) || self.class.responder).call(self, resources, options) end end @@ -269,8 +356,12 @@ module ActionController #:nodoc: end end - # Collects mimes and return the response for the negotiated format. Returns - # nil if :not_acceptable was sent to the client. + # Returns a Collector object containing the appropriate mime-type response + # for the current request, based on the available responses defined by a block. + # In typical usage this is the block passed to +respond_with+ or +respond_to+. + # + # Sends :not_acceptable to the client and returns nil if no suitable format + # is available. # def retrieve_collector_from_mimes(mimes=nil, &block) #:nodoc: mimes ||= collect_mimes_from_class_level @@ -281,6 +372,7 @@ module ActionController #:nodoc: if format self.content_type ||= format.to_s lookup_context.formats = [format.to_sym] + lookup_context.rendered_format = lookup_context.formats.first collector else head :not_acceptable @@ -288,7 +380,30 @@ module ActionController #:nodoc: end end - class Collector #:nodoc: + # A container for responses available from the current controller for + # requests for different mime-types sent to a particular action. + # + # The public controller methods +respond_with+ and +respond_to+ may be called + # with a block that is used to define responses to different mime-types, e.g. + # for +respond_to+ : + # + # respond_to do |format| + # format.html + # format.xml { render :xml => @people } + # end + # + # In this usage, the argument passed to the block (+format+ above) is an + # instance of the ActionController::MimeResponds::Collector class. This + # object serves as a container in which available responses can be stored by + # calling any of the dynamically generated, mime-type-specific methods such + # as +html+, +xml+ etc on the Collector. Each response is represented by a + # corresponding block if present. + # + # A subsequent call to #negotiate_format(request) will enable the Collector + # to determine which specific mime-type it should respond with for the current + # request, with this response then being accessible by calling #response. + # + class Collector include AbstractController::Collector attr_accessor :order, :format diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb index b07742e0e1..3ffb7ef426 100644 --- a/actionpack/lib/action_controller/metal/redirecting.rb +++ b/actionpack/lib/action_controller/metal/redirecting.rb @@ -93,7 +93,7 @@ module ActionController _compute_redirect_to_location options.call else url_for(options) - end.gsub(/[\r\n]/, '') + end.gsub(/[\0\r\n]/, '') end end end diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index afa9243f02..0bff1825d9 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -17,7 +17,6 @@ module ActionController #:nodoc: # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method, # which checks the token and resets the session if it doesn't match what was expected. # A call to this method is generated for new \Rails applications by default. - # You can customize the error message by editing public/422.html. # # The token parameter is named <tt>authenticity_token</tt> by default. The name and # value of this token must be added to every layout that renders forms by including @@ -37,6 +36,10 @@ module ActionController #:nodoc: config_accessor :request_forgery_protection_token self.request_forgery_protection_token ||= :authenticity_token + # Controls how unverified request will be handled + config_accessor :request_forgery_protection_method + self.request_forgery_protection_method ||= :reset_session + # Controls whether request forgery protection is turned on or not. Turned off by default only in test mode. config_accessor :allow_forgery_protection self.allow_forgery_protection = true if allow_forgery_protection.nil? @@ -64,8 +67,10 @@ module ActionController #:nodoc: # Valid Options: # # * <tt>:only/:except</tt> - Passed to the <tt>before_filter</tt> call. Set which actions are verified. + # * <tt>:with</tt> - Set the method to handle unverified request. Valid values: <tt>:exception</tt> and <tt>:reset_session</tt> (default). def protect_from_forgery(options = {}) self.request_forgery_protection_token ||= :authenticity_token + self.request_forgery_protection_method = options.delete(:with) if options.key?(:with) prepend_before_filter :verify_authenticity_token, options end end @@ -80,9 +85,19 @@ module ActionController #:nodoc: end # This is the method that defines the application behavior when a request is found to be unverified. - # By default, \Rails resets the session when it finds an unverified request. + # By default, \Rails uses <tt>request_forgery_protection_method</tt> when it finds an unverified request: + # + # * <tt>:reset_session</tt> - Resets the session. + # * <tt>:exception</tt>: - Raises ActionController::InvalidAuthenticityToken exception. def handle_unverified_request - reset_session + case request_forgery_protection_method + when :exception + raise ActionController::InvalidAuthenticityToken + when :reset_session + reset_session + else + raise ArgumentError, 'Invalid request forgery protection method, use :exception or :reset_session' + end end # Returns true or false if a request is verified. Checks: diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb index ccda01ed44..83407846dc 100644 --- a/actionpack/lib/action_controller/metal/responder.rb +++ b/actionpack/lib/action_controller/metal/responder.rb @@ -63,7 +63,7 @@ module ActionController #:nodoc: # # def create # @project = Project.find(params[:project_id]) - # @task = @project.comments.build(params[:task]) + # @task = @project.tasks.build(params[:task]) # flash[:notice] = 'Task was successfully created.' if @task.save # respond_with(@project, @task) # end @@ -130,6 +130,7 @@ module ActionController #:nodoc: @resources = resources @options = options @action = options.delete(:action) + @default_response = options.delete(:default_response) end delegate :head, :render, :redirect_to, :to => :controller @@ -172,7 +173,7 @@ module ActionController #:nodoc: # responds to :to_format and display it. # def to_format - if get? || !has_errors? + if get? || !has_errors? || response_overridden? default_render else display_errors @@ -226,7 +227,11 @@ module ActionController #:nodoc: # controller. # def default_render - controller.default_render(options) + if @default_response + @default_response.call(options) + else + controller.default_render(options) + end end # Display is just a shortcut to render a resource with the current format. @@ -274,5 +279,9 @@ module ActionController #:nodoc: def json_resource_errors {:errors => resource.errors} end + + def response_overridden? + @default_response.present? + end end end diff --git a/actionpack/lib/action_controller/metal/session_management.rb b/actionpack/lib/action_controller/metal/session_management.rb deleted file mode 100644 index 91d89ff9a4..0000000000 --- a/actionpack/lib/action_controller/metal/session_management.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActionController #:nodoc: - module SessionManagement #:nodoc: - extend ActiveSupport::Concern - - module ClassMethods - - end - end -end diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb index 0b40b1fc4c..8e7b56dbcc 100644 --- a/actionpack/lib/action_controller/metal/url_for.rb +++ b/actionpack/lib/action_controller/metal/url_for.rb @@ -1,25 +1,25 @@ -# Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing -# the <tt>_routes</tt> method. Otherwise, an exception will be raised. -# -# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define -# url options like the +host+. In order to do so, this module requires the host class -# to implement +env+ and +request+, which need to be a Rack-compatible. -# -# Example: -# -# class RootUrl -# include ActionController::UrlFor -# include Rails.application.routes.url_helpers -# -# delegate :env, :request, :to => :controller -# -# def initialize(controller) -# @controller = controller -# @url = root_path # named route from the application. -# end -# end -# module ActionController + # Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing + # the <tt>_routes</tt> method. Otherwise, an exception will be raised. + # + # In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define + # url options like the +host+. In order to do so, this module requires the host class + # to implement +env+ and +request+, which need to be a Rack-compatible. + # + # Example: + # + # class RootUrl + # include ActionController::UrlFor + # include Rails.application.routes.url_helpers + # + # delegate :env, :request, :to => :controller + # + # def initialize(controller) + # @controller = controller + # @url = root_path # named route from the application. + # end + # end + # module UrlFor extend ActiveSupport::Concern @@ -42,6 +42,5 @@ module ActionController @_url_options end end - end end diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb index a288e69649..851a2c4aee 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -3,33 +3,32 @@ require "action_controller" require "action_dispatch/railtie" require "action_view/railtie" require "abstract_controller/railties/routes_helpers" -require "action_controller/railties/paths" +require "action_controller/railties/helpers" module ActionController - class Railtie < Rails::Railtie + class Railtie < Rails::Railtie #:nodoc: config.action_controller = ActiveSupport::OrderedOptions.new - initializer "action_controller.logger" do - ActiveSupport.on_load(:action_controller) { self.logger ||= Rails.logger } - end - - initializer "action_controller.initialize_framework_caches" do - ActiveSupport.on_load(:action_controller) { self.cache_store ||= Rails.cache } - end - initializer "action_controller.assets_config", :group => :all do |app| app.config.action_controller.assets_dir ||= app.config.paths["public"].first end + initializer "action_controller.set_helpers_path" do |app| + ActionController::Helpers.helpers_path = app.helpers_paths + end + initializer "action_controller.set_configs" do |app| paths = app.config.paths options = app.config.action_controller + options.logger ||= Rails.logger + options.cache_store ||= Rails.cache + options.javascripts_dir ||= paths["public/javascripts"].first options.stylesheets_dir ||= paths["public/stylesheets"].first options.page_cache_directory ||= paths["public"].first - # make sure readers methods get compiled + # Ensure readers methods get compiled options.asset_path ||= app.config.asset_path options.asset_host ||= app.config.asset_host options.relative_url_root ||= app.config.relative_url_root @@ -37,8 +36,16 @@ module ActionController ActiveSupport.on_load(:action_controller) do include app.routes.mounted_helpers extend ::AbstractController::Railties::RoutesHelpers.with(app.routes) - extend ::ActionController::Railties::Paths.with(app) - options.each { |k,v| send("#{k}=", v) } + extend ::ActionController::Railties::Helpers + + options.each do |k,v| + k = "#{k}=" + if respond_to?(k) + send(k, v) + elsif !Base.respond_to?(k) + raise "Invalid option key: #{k}" + end + end end end diff --git a/actionpack/lib/action_controller/railties/helpers.rb b/actionpack/lib/action_controller/railties/helpers.rb new file mode 100644 index 0000000000..3985c6b273 --- /dev/null +++ b/actionpack/lib/action_controller/railties/helpers.rb @@ -0,0 +1,22 @@ +module ActionController + module Railties + module Helpers + def inherited(klass) + super + return unless klass.respond_to?(:helpers_path=) + + if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) } + paths = namespace.railtie_helpers_paths + else + paths = ActionController::Helpers.helpers_path + end + + klass.helpers_path = paths + + if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers + klass.helper :all + end + end + end + end +end diff --git a/actionpack/lib/action_controller/railties/paths.rb b/actionpack/lib/action_controller/railties/paths.rb deleted file mode 100644 index bbe63149ad..0000000000 --- a/actionpack/lib/action_controller/railties/paths.rb +++ /dev/null @@ -1,25 +0,0 @@ -module ActionController - module Railties - module Paths - def self.with(app) - Module.new do - define_method(:inherited) do |klass| - super(klass) - - if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) } - paths = namespace.railtie_helpers_paths - else - paths = app.helpers_paths - end - - klass.helpers_path = paths - - if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers - klass.helper :all - end - end - end - end - end - end -end diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb index 9c38ff44d8..18dda978b3 100644 --- a/actionpack/lib/action_controller/record_identifier.rb +++ b/actionpack/lib/action_controller/record_identifier.rb @@ -2,8 +2,8 @@ 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 - # Active Resources or pretty much any other model type that has an id. These patterns are then used to try elevate - # the view actions to a higher logical level. Example: + # pretty much any other model type that has an id. These patterns are then used to try elevate the view actions to + # a higher logical level. Example: # # # routes # resources :posts diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 3509e74d5e..9bd2e622ad 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -56,6 +56,9 @@ module ActionController # # assert that the "new" view template was rendered # assert_template "new" # + # # assert that the exact template "admin/posts/new" was rendered + # assert_template %r{\Aadmin/posts/new\Z} + # # # assert that the "_customer" partial was rendered twice # assert_template :partial => '_customer', :count => 2 # @@ -69,12 +72,16 @@ module ActionController # assert_template :partial => '_customer', :locals => { :customer => @customer } # def assert_template(options = {}, message = nil) + # Force body to be read in case the + # template is being streamed + response.body + case options - when NilClass, String, Symbol + when NilClass, String, Symbol, Regexp options = options.to_s if Symbol === options rendered = @templates msg = message || sprintf("expecting <%s> but rendering with <%s>", - options, rendered.keys) + options.inspect, rendered.keys) assert_block(msg) do if options rendered.any? { |t,num| t.match(options) } @@ -117,6 +124,8 @@ module ActionController assert @partials.empty?, "Expected no partials to be rendered" end + else + raise ArgumentError, "assert_template only accepts a String, Symbol, Hash, Regexp, or nil" end end end @@ -470,7 +479,6 @@ module ActionController @request.session["flash"].sweep @controller.request = @request - @controller.params.merge!(parameters) build_request_uri(action, parameters) @controller.class.class_eval { include Testing } @controller.recycle! @@ -496,11 +504,6 @@ module ActionController end end - # Cause the action to be rescued according to the regular rules for rescue_action when the visitor is not local - def rescue_action_in_public! - @request.remote_addr = '208.77.188.166' # example.com - end - included do include ActionController::TemplateAssertions include ActionDispatch::Assertions diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb index 24ffc28710..e9b50ff8ce 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb +++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb @@ -5,6 +5,7 @@ require 'active_support/core_ext/class/attribute' module HTML class Sanitizer def sanitize(text, options = {}) + validate_options(options) return text unless sanitizeable?(text) tokenize(text, options).join end @@ -27,6 +28,16 @@ module HTML def process_node(node, result, options) result << node.to_s end + + def validate_options(options) + if options[:tags] && !options[:tags].is_a?(Enumerable) + raise ArgumentError, "You should pass :tags as an Enumerable" + end + + if options[:attributes] && !options[:attributes].is_a?(Enumerable) + raise ArgumentError, "You should pass :attributes as an Enumerable" + end + end end class FullSanitizer < Sanitizer diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb index a9542a7d1b..e3b04ac097 100644 --- a/actionpack/lib/action_dispatch.rb +++ b/actionpack/lib/action_dispatch.rb @@ -61,6 +61,7 @@ module ActionDispatch autoload :Reloader autoload :RemoteIp autoload :ShowExceptions + autoload :SSL autoload :Static end diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 2152351703..e039eb1288 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -82,7 +82,7 @@ module Mime class << self TRAILING_STAR_REGEXP = /(text|application)\/\*/ - Q_SEPARATOR_REGEXP = /;\s*q=/ + PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/ def lookup(string) LOOKUP[string] @@ -109,7 +109,7 @@ module Mime def parse(accept_header) if accept_header !~ /,/ - accept_header = accept_header.split(Q_SEPARATOR_REGEXP).first + accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first if accept_header =~ TRAILING_STAR_REGEXP parse_data_with_trailing_star($1) else @@ -119,7 +119,7 @@ module Mime # keep track of creation order to keep the subsequent sort stable list, index = [], 0 accept_header.split(/,/).each do |header| - params, q = header.split(Q_SEPARATOR_REGEXP) + params, q = header.split(PARAMETER_SEPARATOR_REGEXP) if params.present? params.strip! diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index de014a9c00..796e0dbc45 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -17,7 +17,8 @@ module ActionDispatch include ActionDispatch::Http::Upload include ActionDispatch::Http::URL - LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze + LOCALHOST = Regexp.union [/^127\.0\.0\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/] + ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE PATH_TRANSLATED REMOTE_HOST REMOTE_IDENT REMOTE_USER REMOTE_ADDR @@ -250,7 +251,7 @@ module ActionDispatch # True if the request came from localhost, 127.0.0.1. def local? - LOCALHOST.any? { |local_ip| local_ip === remote_addr && local_ip === remote_ip } + LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip end private diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index 84732085f0..078229efd2 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -51,12 +51,13 @@ module ActionDispatch # :nodoc: # If a character set has been defined for this response (see charset=) then # the character set information will also be included in the content type # information. - attr_accessor :charset, :content_type + attr_accessor :charset + attr_reader :content_type CONTENT_TYPE = "Content-Type".freeze SET_COOKIE = "Set-Cookie".freeze LOCATION = "Location".freeze - + cattr_accessor(:default_charset) { "utf-8" } include Rack::Response::Helpers @@ -83,6 +84,10 @@ module ActionDispatch # :nodoc: @status = Rack::Utils.status_code(status) end + def content_type=(content_type) + @content_type = content_type.to_s + end + # The response code of the request def response_code @status diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb index 5ab99d1061..ce8c2729e9 100644 --- a/actionpack/lib/action_dispatch/http/upload.rb +++ b/actionpack/lib/action_dispatch/http/upload.rb @@ -4,11 +4,12 @@ module ActionDispatch attr_accessor :original_filename, :content_type, :tempfile, :headers def initialize(hash) + @tempfile = hash[:tempfile] + raise(ArgumentError, ':tempfile is required') unless @tempfile + @original_filename = encode_filename(hash[:filename]) @content_type = hash[:type] @headers = hash[:head] - @tempfile = hash[:tempfile] - raise(ArgumentError, ':tempfile is required') unless @tempfile end def read(*args) @@ -16,18 +17,15 @@ module ActionDispatch end # Delegate these methods to the tempfile. - [:open, :path, :rewind, :size].each do |method| + [:open, :path, :rewind, :size, :eof?].each do |method| class_eval "def #{method}; @tempfile.#{method}; end" end - + private + def encode_filename(filename) # Encode the filename in the utf8 encoding, unless it is nil - if filename - filename.force_encoding("UTF-8").encode! - else - filename - end + filename.force_encoding("UTF-8").encode! if filename end end diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 80ffbe575b..f9dae5dad7 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -40,7 +40,9 @@ module ActionDispatch rewritten_url << ":#{options.delete(:port)}" if options[:port] end - path = options.delete(:path) || '' + path = "" + path << options.delete(:script_name).to_s.chomp("/") + path << options.delete(:path).to_s params = options[:params] || {} params.reject! {|k,v| v.to_param.nil? } diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 25f1db8228..0c717c8503 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -273,10 +273,6 @@ module ActionDispatch @parent_jar[key] = options end - def signed - @signed ||= SignedCookieJar.new(self, @secret) - end - def method_missing(method, *arguments, &block) @parent_jar.send(method, *arguments, &block) end diff --git a/actionpack/lib/action_dispatch/middleware/request_id.rb b/actionpack/lib/action_dispatch/middleware/request_id.rb index d5a0b80fd5..6fff94707c 100644 --- a/actionpack/lib/action_dispatch/middleware/request_id.rb +++ b/actionpack/lib/action_dispatch/middleware/request_id.rb @@ -19,10 +19,7 @@ module ActionDispatch def call(env) env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id - status, headers, body = @app.call(env) - - headers["X-Request-Id"] = env["action_dispatch.request_id"] - [ status, headers, body ] + @app.call(env).tap { |status, headers, body| headers["X-Request-Id"] = env["action_dispatch.request_id"] } end private diff --git a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb index d3b6fd12fa..1db6194271 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb @@ -1,5 +1,4 @@ require 'action_dispatch/middleware/session/abstract_store' -require 'rack/session/memcache' module ActionDispatch module Session diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb index 8ebf870b95..a4866f5a8f 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb @@ -59,7 +59,8 @@ module ActionDispatch end def set_session(env, sid, session_data, options) - session_data.merge("session_id" => sid) + session_data["session_id"] = sid + session_data end def set_cookie(env, session_id, cookie) diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 836136eb95..ab740a0190 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -9,7 +9,7 @@ module ActionDispatch # of ShowExceptions. Everytime there is an exception, ShowExceptions will # store the exception in env["action_dispatch.exception"], rewrite the # PATH_INFO to the exception status code and call the rack app. - # + # # If the application returns a "X-Cascade" pass response, this middleware # will send an empty response as result with the correct status code. # If any exception happens inside the exceptions app, this middleware diff --git a/actionpack/lib/action_dispatch/middleware/ssl.rb b/actionpack/lib/action_dispatch/middleware/ssl.rb new file mode 100644 index 0000000000..9098f4e170 --- /dev/null +++ b/actionpack/lib/action_dispatch/middleware/ssl.rb @@ -0,0 +1,70 @@ +module ActionDispatch + class SSL + YEAR = 31536000 + + def self.default_hsts_options + { :expires => YEAR, :subdomains => false } + end + + def initialize(app, options = {}) + @app = app + + @hsts = options.fetch(:hsts, {}) + @hsts = {} if @hsts == true + @hsts = self.class.default_hsts_options.merge(@hsts) if @hsts + + @host = options[:host] + @port = options[:port] + end + + def call(env) + request = Request.new(env) + + if request.ssl? + status, headers, body = @app.call(env) + headers = hsts_headers.merge(headers) + flag_cookies_as_secure!(headers) + [status, headers, body] + else + redirect_to_https(request) + end + end + + private + def redirect_to_https(request) + url = URI(request.url) + url.scheme = "https" + url.host = @host if @host + url.port = @port if @port + headers = hsts_headers.merge('Content-Type' => 'text/html', + 'Location' => url.to_s) + + [301, headers, []] + end + + # http://tools.ietf.org/html/draft-hodges-strict-transport-sec-02 + def hsts_headers + if @hsts + value = "max-age=#{@hsts[:expires]}" + value += "; includeSubDomains" if @hsts[:subdomains] + { 'Strict-Transport-Security' => value } + else + {} + end + end + + def flag_cookies_as_secure!(headers) + if cookies = headers['Set-Cookie'] + cookies = cookies.split("\n") + + headers['Set-Cookie'] = cookies.map { |cookie| + if cookie !~ /;\s+secure(;|$)/ + "#{cookie}; secure" + else + cookie + end + }.join("\n") + end + end + end +end diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 63b7422287..9073e6582d 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -39,6 +39,7 @@ module ActionDispatch end def escape_glob_chars(path) + path.force_encoding('binary') if path.respond_to? :force_encoding path.gsub(/[*?{}\[\]]/, "\\\\\\&") end end diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb index 35f901c575..62f906219c 100644 --- a/actionpack/lib/action_dispatch/railtie.rb +++ b/actionpack/lib/action_dispatch/railtie.rb @@ -16,7 +16,7 @@ module ActionDispatch config.action_dispatch.rack_cache = { :metastore => "rails:/", :entitystore => "rails:/", - :verbose => true + :verbose => false } initializer "action_dispatch.configure" do |app| diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 02a27110e4..fccbff1749 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1,6 +1,6 @@ require 'active_support/core_ext/hash/except' require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/object/inclusion' +require 'active_support/core_ext/enumerable' require 'active_support/inflector' require 'action_dispatch/routing/redirection' @@ -254,10 +254,15 @@ module ActionDispatch # # For options, see +match+, as +root+ uses it internally. # + # You can also pass a string which will expand + # + # root 'pages#main' + # # You should put the root route at the top of <tt>config/routes.rb</tt>, # because this means it will be matched first. As this is the most popular route # of most Rails applications, this is beneficial. def root(options = {}) + options = { :to => options } if options.is_a?(String) match '/', { :as => :root }.merge(options) end @@ -446,7 +451,11 @@ module ActionDispatch _route = @set.named_routes.routes[name.to_sym] _routes = @set app.routes.define_mounted_helper(name) - app.routes.class_eval do + app.routes.singleton_class.class_eval do + define_method :mounted? do + true + end + define_method :_generate_prefix do |options| prefix_options = options.slice(*_route.segment_keys) # we must actually delete prefix segment keys to avoid passing them to next url_for @@ -871,17 +880,18 @@ module ActionDispatch # CANONICAL_ACTIONS holds all actions that does not need a prefix or # a path appended since they fit properly in their scope level. VALID_ON_OPTIONS = [:new, :collection, :member] - RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except] + RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param] CANONICAL_ACTIONS = %w(index create new show update destroy) class Resource #:nodoc: - attr_reader :controller, :path, :options + attr_reader :controller, :path, :options, :param def initialize(entities, options = {}) @name = entities.to_s @path = (options[:path] || @name).to_s @controller = (options[:controller] || @name).to_s @as = options[:as] + @param = options[:param] || :id @options = options end @@ -926,7 +936,7 @@ module ActionDispatch alias :collection_scope :path def member_scope - "#{path}/:id" + "#{path}/:#{param}" end def new_scope(new_path) @@ -934,7 +944,7 @@ module ActionDispatch end def nested_scope - "#{path}/:#{singular}_id" + "#{path}/:#{singular}_#{param}" end end @@ -1125,6 +1135,25 @@ module ActionDispatch # comment PATCH/PUT /sekret/comments/:id(.:format) # comment DELETE /sekret/comments/:id(.:format) # + # [:shallow_prefix] + # Prefixes nested shallow route names with specified prefix. + # + # scope :shallow_prefix => "sekret" do + # resources :posts do + # resources :comments, :shallow => true + # end + # end + # + # The +comments+ resource here will have the following routes generated for it: + # + # post_comments GET /posts/:post_id/comments(.:format) + # post_comments POST /posts/:post_id/comments(.:format) + # new_post_comment GET /posts/:post_id/comments/new(.:format) + # edit_sekret_comment GET /comments/:id/edit(.:format) + # sekret_comment GET /comments/:id(.:format) + # sekret_comment PATCH/PUT /comments/:id(.:format) + # sekret_comment DELETE /comments/:id(.:format) + # # === Examples # # # routes call <tt>Admin::PostsController</tt> diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 57c6972078..30e9e5634b 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -191,14 +191,50 @@ module ActionDispatch selector = url_helper_name(name, kind) hash_access_method = hash_access_name(name, kind) - @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 - remove_possible_method :#{selector} - def #{selector}(*args) - url_for(#{hash_access_method}(*args)) - end - END_EVAL + if optimize_helper?(route) + @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 + remove_possible_method :#{selector} + def #{selector}(*args) + if args.size == #{route.required_parts.size} && !args.last.is_a?(Hash) && optimize_routes_generation? + options = #{options.inspect}.merge!(url_options) + options[:path] = "#{optimized_helper(route)}" + ActionDispatch::Http::URL.url_for(options) + else + url_for(#{hash_access_method}(*args)) + end + end + END_EVAL + else + @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 + remove_possible_method :#{selector} + def #{selector}(*args) + url_for(#{hash_access_method}(*args)) + end + END_EVAL + end + helpers << selector end + + # Clause check about when we need to generate an optimized helper. + def optimize_helper?(route) #:nodoc: + route.ast.grep(Journey::Nodes::Star).empty? && route.requirements.except(:controller, :action).empty? + end + + # Generates the interpolation to be used in the optimized helper. + def optimized_helper(route) + string_route = route.ast.to_s + + while string_route.gsub!(/\([^\)]*\)/, "") + true + end + + route.required_parts.each_with_index do |part, i| + string_route.gsub!(part.inspect, "\#{Journey::Router::Utils.escape_fragment(args[#{i}].to_param)}") + end + + string_route + end end attr_accessor :formatter, :set, :named_routes, :default_scope, :router @@ -323,7 +359,7 @@ module ActionDispatch # Rails.application.routes.url_helpers.url_for(args) @_routes = routes class << self - delegate :url_for, :to => '@_routes' + delegate :url_for, :optimize_routes_generation?, :to => '@_routes' end # Make named_routes available in the module singleton @@ -557,6 +593,14 @@ module ActionDispatch RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length, :trailing_slash, :anchor, :params, :only_path, :script_name] + def mounted? + false + end + + def optimize_routes_generation? + !mounted? && default_url_options.empty? + end + def _generate_prefix(options = {}) nil end @@ -568,19 +612,17 @@ module ActionDispatch user, password = extract_authentication(options) path_segments = options.delete(:_path_segments) - script_name = options.delete(:script_name) - - path = (script_name.blank? ? _generate_prefix(options) : script_name.chomp('/')).to_s + script_name = options.delete(:script_name).presence || _generate_prefix(options) path_options = options.except(*RESERVED_OPTIONS) path_options = yield(path_options) if block_given? - path_addition, params = generate(path_options, path_segments || {}) - path << path_addition + path, params = generate(path_options, path_segments || {}) params.merge!(options[:params] || {}) ActionDispatch::Http::URL.url_for(options.merge!({ :path => path, + :script_name => script_name, :params => params, :user => user, :password => password @@ -594,6 +636,7 @@ module ActionDispatch def recognize_path(path, environment = {}) method = (environment[:method] || "GET").to_s.upcase path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://} + extras = environment[:extras] || {} begin env = Rack::MockRequest.env_for(path, {:method => method}) @@ -603,6 +646,7 @@ module ActionDispatch req = @request_class.new(env) @router.recognize(req) do |route, matches, params| + params.merge!(extras) params.each do |key, value| if value.is_a?(String) value = value.dup.force_encoding(Encoding::BINARY) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index ee6616c5d3..94db36ce1f 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -102,6 +102,9 @@ module ActionDispatch super end + # Hook overriden in controller to add request information + # with `default_url_options`. Application logic should not + # go into url_options. def url_options default_url_options end @@ -152,6 +155,11 @@ module ActionDispatch protected + def optimize_routes_generation? + return @_optimized_routes if defined?(@_optimized_routes) + @_optimized_routes = _routes.optimize_routes_generation? && default_url_options.empty? + end + def _with_routes(routes) old_routes, @_routes = @_routes, routes yield diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index 094cfbfc76..33f8f526b5 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -4,11 +4,9 @@ module ActionDispatch module Assertions # A small suite of assertions that test responses from \Rails applications. module ResponseAssertions - extend ActiveSupport::Concern - # Asserts that the response is one of the following types: # - # * <tt>:success</tt> - Status code was 200 + # * <tt>:success</tt> - Status code was in the 200-299 range # * <tt>:redirect</tt> - Status code was in the 300-399 range # * <tt>:missing</tt> - Status code was 404 # * <tt>:error</tt> - Status code was in the 500-599 range @@ -83,7 +81,7 @@ module ActionDispatch refer else @controller.url_for(fragment) - end.gsub(/[\r\n]/, '') + end.gsub(/[\0\r\n]/, '') end end end diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 1552676fbb..1f4b905d18 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -39,10 +39,9 @@ module ActionDispatch # # Test a custom route # assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1') def assert_recognizes(expected_options, path, extras={}, message=nil) - request = recognized_request_for(path) + request = recognized_request_for(path, extras) expected_options = expected_options.clone - extras.each_key { |key| expected_options.delete key } unless extras.nil? expected_options.stringify_keys! @@ -181,7 +180,7 @@ module ActionDispatch private # Recognizes the route for a given path. - def recognized_request_for(path) + def recognized_request_for(path, extras = {}) if path.is_a?(Hash) method = path[:method] path = path[:path] @@ -209,7 +208,7 @@ module ActionDispatch request.request_method = method if method - params = @routes.recognize_path(path, { :method => method }) + params = @routes.recognize_path(path, { :method => method, :extras => extras }) request.path_parameters = params.with_indifferent_access request diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 8eed85bce2..ea1ed20f3c 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -269,6 +269,7 @@ module ActionDispatch end end text.strip! unless NO_STRIP.include?(match.name) + text.sub!(/\A\n/, '') if match.name == "textarea" unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s) content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, text) true diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index 7280e9a93b..d04be2099c 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -1,6 +1,5 @@ require 'active_support/core_ext/object/blank' require 'active_support/core_ext/hash/indifferent_access' -require 'active_support/core_ext/hash/reverse_merge' require 'rack/utils' module ActionDispatch diff --git a/actionpack/lib/action_view/asset_paths.rb b/actionpack/lib/action_view/asset_paths.rb index 2a28e780bf..add8d94b70 100644 --- a/actionpack/lib/action_view/asset_paths.rb +++ b/actionpack/lib/action_view/asset_paths.rb @@ -117,7 +117,7 @@ module ActionView end def relative_url_root - config.relative_url_root + config.relative_url_root || current_request.try(:script_name) end def asset_host_config diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 23329d7f35..f3315948b4 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -141,6 +141,12 @@ module ActionView #:nodoc: cattr_accessor :streaming_completion_on_exception @@streaming_completion_on_exception = %("><script type="text/javascript">window.location = "/500.html"</script></html>) + # Specify whether rendering within namespaced controllers should prefix + # the partial paths for ActiveModel objects with the namespace. + # (e.g., an Admin::PostsController would render @post using /admin/posts/_post.erb) + cattr_accessor :prefix_partial_path_with_controller_namespace + @@prefix_partial_path_with_controller_namespace = true + class_attribute :helpers class_attribute :_routes class_attribute :logger @@ -194,7 +200,7 @@ module ActionView #:nodoc: # TODO Provide a new API for AV::Base and deprecate this one. if context.is_a?(ActionView::Renderer) @view_renderer = context - elsif + else lookup_context = context.is_a?(ActionView::LookupContext) ? context : ActionView::LookupContext.new(context) lookup_context.formats = formats if formats diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb index 662adbe183..2f8b28c82b 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb @@ -24,9 +24,10 @@ module ActionView # server by setting ActionController::Base.asset_host in the application # configuration, typically in <tt>config/environments/production.rb</tt>. # For example, you'd define <tt>assets.example.com</tt> to be your asset - # host this way: + # host this way, inside the <tt>configure</tt> block of your environment-specific + # configuration files or <tt>config/application.rb</tt>: # - # ActionController::Base.asset_host = "assets.example.com" + # config.action_controller.asset_host = "assets.example.com" # # Helpers take that into account: # @@ -384,7 +385,7 @@ module ActionView # image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # => # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" /> def image_tag(source, options={}) - options = options.dup.symbolize_keys! + options = options.symbolize_keys src = options[:src] = path_to_image(source) @@ -477,7 +478,7 @@ module ActionView end def multiple_sources_tag(type, sources) - options = sources.extract_options!.dup.symbolize_keys! + options = sources.extract_options!.symbolize_keys sources.flatten! yield options if block_given? diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb index 73824dc1f8..70164217de 100644 --- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb +++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb @@ -176,6 +176,7 @@ module ActionView # * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists. # * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record. # * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}" + # * <tt>:type</tt>: The TYPE for this entry. Defaults to "text/html". def entry(record, options = {}) @xml.entry do @xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}") @@ -188,7 +189,9 @@ module ActionView @xml.updated((options[:updated] || record.updated_at).xmlschema) end - @xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:url] || @view.polymorphic_url(record)) + type = options.fetch(:type) { 'text/html' } + + @xml.link(:rel => 'alternate', :type => type, :href => options[:url] || @view.polymorphic_url(record)) yield AtomBuilder.new(@xml) end diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb index 17bbfe2efd..278139cadb 100644 --- a/actionpack/lib/action_view/helpers/capture_helper.rb +++ b/actionpack/lib/action_view/helpers/capture_helper.rb @@ -215,7 +215,7 @@ module ActionView def flush_output_buffer #:nodoc: if output_buffer && !output_buffer.empty? response.body_parts << output_buffer - self.output_buffer = output_buffer[0,0] + self.output_buffer = output_buffer.respond_to?(:clone_empty) ? output_buffer.clone_empty : output_buffer[0, 0] nil end end diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 2d37923825..cb46f26d99 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -625,13 +625,18 @@ module ActionView # time_tag Date.today, :pubdate => true # => # <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time> # - def time_tag(date_or_time, *args) + # <%= time_tag Time.now do %> + # <span>Right now</span> + # <% end %> + # # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time> + # + def time_tag(date_or_time, *args, &block) options = args.extract_options! format = options.delete(:format) || :long content = args.first || I18n.l(date_or_time, :format => format) datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.rfc3339 - content_tag(:time, content, options.reverse_merge(:datetime => datetime)) + content_tag(:time, content, options.reverse_merge(:datetime => datetime), &block) end end @@ -669,11 +674,7 @@ module ActionView @options[:discard_minute] ||= true if @options[:discard_hour] @options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute] - # If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are - # valid (otherwise it could be 31 and February wouldn't be a valid date) - if @datetime && @options[:discard_day] && !@options[:discard_month] - @datetime = @datetime.change(:day => 1) - end + set_day_if_discarded if @options[:tag] && @options[:ignore_date] select_time @@ -696,11 +697,7 @@ module ActionView @options[:discard_month] ||= true unless order.include?(:month) @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day) - # If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are - # valid (otherwise it could be 31 and February wouldn't be a valid date) - if @datetime && @options[:discard_day] && !@options[:discard_month] - @datetime = @datetime.change(:day => 1) - end + set_day_if_discarded [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) } @@ -798,7 +795,15 @@ module ActionView private %w( sec min hour day month year ).each do |method| define_method(method) do - @datetime.kind_of?(Fixnum) ? @datetime : @datetime.send(method) if @datetime + @datetime.kind_of?(Numeric) ? @datetime : @datetime.send(method) if @datetime + end + end + + # If the day is hidden, the day should be set to the 1st so all month and year choices are + # valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid. + def set_day_if_discarded + if @datetime && @options[:discard_day] + @datetime = @datetime.change(:day => 1) end end @@ -972,7 +977,10 @@ module ActionView # Returns the id attribute for the input tag. # => "post_written_on_1i" def input_id_from_type(type) - input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '') + id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '') + id = @options[:namespace] + '_' + id if @options[:namespace] + + id end # Given an ordering of datetime components, create the selection HTML diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index 53ae8b66da..6219a7a924 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -9,6 +9,7 @@ require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/object/blank' require 'active_support/core_ext/string/output_safety' require 'active_support/core_ext/array/extract_options' +require 'active_support/deprecation' module ActionView # = Action View Form Helpers @@ -16,17 +17,28 @@ module ActionView # Form helpers are designed to make working with resources much easier # compared to using vanilla HTML. # - # Forms for models are created with +form_for+. That method yields a form - # builder that knows the model the form is about. The form builder is thus - # able to generate default values for input fields that correspond to model - # attributes, and also convenient names, IDs, endpoints, etc. + # Typically, a form designed to create or update a resource reflects the + # identity of the resource in several ways: (i) the url that the form is + # sent to (the form element's +action+ attribute) should result in a request + # being routed to the appropriate controller action (with the appropriate <tt>:id</tt> + # parameter in the case of an existing resource), (ii) input fields should + # be named in such a way that in the controller their values appear in the + # appropriate places within the +params+ hash, and (iii) for an existing record, + # when the form is initially displayed, input fields corresponding to attributes + # of the resource should show the current values of those attributes. # - # Conventions in the generated field names allow controllers to receive form - # data nicely structured in +params+ with no effort on your side. + # In Rails, this is usually achieved by creating the form using +form_for+ and + # a number of related helper methods. +form_for+ generates an appropriate <tt>form</tt> + # tag and yields a form builder object that knows the model the form is about. + # Input fields are created by calling methods defined on the form builder, which + # means they are able to generate the appropriate names and default values + # corresponding to the model attributes, as well as convenient IDs, etc. + # Conventions in the generated field names allow controllers to receive form data + # nicely structured in +params+ with no effort on your side. # # For example, to create a new person you typically set up a new instance of # +Person+ in the <tt>PeopleController#new</tt> action, <tt>@person</tt>, and - # pass it to +form_for+: + # in the view template pass that object to +form_for+: # # <%= form_for @person do |f| %> # <%= f.label :first_name %>: @@ -45,10 +57,10 @@ module ActionView # <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" /> # </div> # <label for="person_first_name">First name</label>: - # <input id="person_first_name" name="person[first_name]" size="30" type="text" /><br /> + # <input id="person_first_name" name="person[first_name]" type="text" /><br /> # # <label for="person_last_name">Last name</label>: - # <input id="person_last_name" name="person[last_name]" size="30" type="text" /><br /> + # <input id="person_last_name" name="person[last_name]" type="text" /><br /> # # <input name="commit" type="submit" value="Create Person" /> # </form> @@ -76,10 +88,10 @@ module ActionView # <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" /> # </div> # <label for="person_first_name">First name</label>: - # <input id="person_first_name" name="person[first_name]" size="30" type="text" value="John" /><br /> + # <input id="person_first_name" name="person[first_name]" type="text" value="John" /><br /> # # <label for="person_last_name">Last name</label>: - # <input id="person_last_name" name="person[last_name]" size="30" type="text" value="Smith" /><br /> + # <input id="person_last_name" name="person[last_name]" type="text" value="Smith" /><br /> # # <input name="commit" type="submit" value="Update Person" /> # </form> @@ -109,29 +121,14 @@ module ActionView object.respond_to?(:to_model) ? object.to_model : object end - # Creates a form and a scope around a specific model object that is used - # as a base for questioning about values for the fields. + # Creates a form that allows the user to create or update the attributes + # of a specific model object. # - # Rails provides succinct resource-oriented form generation with +form_for+ - # like this: - # - # <%= form_for @offer do |f| %> - # <%= f.label :version, 'Version' %>: - # <%= f.text_field :version %><br /> - # <%= f.label :author, 'Author' %>: - # <%= f.text_field :author %><br /> - # <%= f.submit %> - # <% end %> - # - # There, +form_for+ is able to generate the rest of RESTful form - # parameters based on introspection on the record, but to understand what - # it does we need to dig first into the alternative generic usage it is - # based upon. - # - # === Generic form_for - # - # The generic way to call +form_for+ yields a form builder around a - # model: + # The method can be used in several slightly different ways, depending on + # how much you wish to rely on Rails to infer automatically from the model + # how the form should be constructed. For a generic model object, a form + # can be created by passing +form_for+ a string or symbol representing + # the object we are concerned with: # # <%= form_for :person do |f| %> # First name: <%= f.text_field :first_name %><br /> @@ -141,24 +138,39 @@ module ActionView # <%= f.submit %> # <% end %> # - # There, the argument is a symbol or string with the name of the - # object the form is about. - # - # The form builder acts as a regular form helper that somehow carries the - # model. Thus, the idea is that + # The variable +f+ yielded to the block is a FormBuilder object that + # incorporates the knowledge about the model object represented by + # <tt>:person</tt> passed to +form_for+. Methods defined on the FormBuilder + # are used to generate fields bound to this model. Thus, for example, # # <%= f.text_field :first_name %> # - # gets expanded to + # will get expanded to # # <%= text_field :person, :first_name %> + # which results in an html <tt><input></tt> tag whose +name+ attribute is + # <tt>person[first_name]</tt>. This means that when the form is submitted, + # the value entered by the user will be available in the controller as + # <tt>params[:person][:first_name]</tt>. + # + # For fields generated in this way using the FormBuilder, + # if <tt>:person</tt> also happens to be the name of an instance variable + # <tt>@person</tt>, the default value of the field shown when the form is + # initially displayed (e.g. in the situation where you are editing an + # existing record) will be the value of the corresponding attribute of + # <tt>@person</tt>. # # The rightmost argument to +form_for+ is an - # optional hash of options: - # - # * <tt>:url</tt> - The URL the form is submitted to. It takes the same - # fields you pass to +url_for+ or +link_to+. In particular you may pass - # here a named route directly as well. Defaults to the current action. + # optional hash of options - + # + # * <tt>:url</tt> - The URL the form is to be submitted to. This may be + # represented in the same way as values passed to +url_for+ or +link_to+. + # So for example you may use a named route directly. When the model is + # represented by a string or symbol, as in the example above, if the + # <tt>:url</tt> option is not specified, by default the form will be + # sent back to the current url (We will describe below an alternative + # resource-oriented usage of +form_for+ in which the URL does not need + # to be specified explicitly). # * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of # id attributes on form elements. The namespace attribute will be prefixed # with underscore on the generated HTML id. @@ -168,7 +180,7 @@ module ActionView # possible to use both the stand-alone FormHelper methods and methods # from FormTagHelper. For example: # - # <%= form_for @person do |f| %> + # <%= form_for :person do |f| %> # First name: <%= f.text_field :first_name %> # Last name : <%= f.text_field :last_name %> # Biography : <%= text_area :person, :biography %> @@ -180,26 +192,65 @@ module ActionView # are designed to work with an object as base, like # FormOptionHelper#collection_select and DateHelper#datetime_select. # - # === Resource-oriented style + # === #form_for with a model object + # + # In the examples above, the object to be created or edited was + # represented by a symbol passed to +form_for+, and we noted that + # a string can also be used equivalently. It is also possible, however, + # to pass a model object itself to +form_for+. For example, if <tt>@post</tt> + # is an existing record you wish to edit, you can create the form using + # + # <%= form_for @post do |f| %> + # ... + # <% end %> + # + # This behaves in almost the same way as outlined previously, with a + # couple of small exceptions. First, the prefix used to name the input + # elements within the form (hence the key that denotes them in the +params+ + # hash) is actually derived from the object's _class_, e.g. <tt>params[:post]</tt> + # if the object's class is +Post+. However, this can be overwritten using + # the <tt>:as</tt> option, e.g. - + # + # <%= form_for(@person, :as => :client) do |f| %> + # ... + # <% end %> # - # As we said above, in addition to manually configuring the +form_for+ - # call, you can rely on automated resource identification, which will use - # the conventions and named routes of that approach. This is the - # preferred way to use +form_for+ nowadays. + # would result in <tt>params[:client]</tt>. # - # For example, if <tt>@post</tt> is an existing record you want to edit + # Secondly, the field values shown when the form is initially displayed + # are taken from the attributes of the object passed to +form_for+, + # regardless of whether the object is an instance + # variable. So, for example, if we had a _local_ variable +post+ + # representing an existing record, + # + # <%= form_for post do |f| %> + # ... + # <% end %> + # + # would produce a form with fields whose initial state reflect the current + # values of the attributes of +post+. + # + # === Resource-oriented style + # + # In the examples just shown, although not indicated explicitly, we still + # need to use the <tt>:url</tt> option in order to specify where the + # form is going to be sent. However, further simplification is possible + # if the record passed to +form_for+ is a _resource_, i.e. it corresponds + # to a set of RESTful routes, e.g. defined using the +resources+ method + # in <tt>config/routes.rb</tt>. In this case Rails will simply infer the + # appropriate URL from the record itself. For example, # # <%= form_for @post do |f| %> # ... # <% end %> # - # is equivalent to something like: + # is then equivalent to something like: # # <%= form_for @post, :as => :post, :url => post_path(@post), :method => :put, :html => { :class => "edit_post", :id => "edit_post_45" } do |f| %> # ... # <% end %> # - # And for new records + # And for a new record # # <%= form_for(Post.new) do |f| %> # ... @@ -211,7 +262,7 @@ module ActionView # ... # <% end %> # - # You can also overwrite the individual conventions, like this: + # However you can still overwrite individual conventions, such as: # # <%= form_for(@post, :url => super_posts_path) do |f| %> # ... @@ -223,13 +274,6 @@ module ActionView # ... # <% end %> # - # If you have an object that needs to be represented as a different - # parameter, like a Person that acts as a Client: - # - # <%= form_for(@person, :as => :client) do |f| %> - # ... - # <% end %> - # # For namespaced routes, like +admin_post_url+: # # <%= form_for([:admin, @post]) do |f| %> @@ -252,9 +296,9 @@ module ActionView # # :method => (:get|:post|:patch|:put|:delete) # - # in the options hash. If the verb is not GET or POST, which are natively supported by HTML forms, the - # form will be set to POST and a hidden input called _method will carry the intended verb for the server - # to interpret. + # in the options hash. If the verb is not GET or POST, which are natively + # supported by HTML forms, the form will be set to POST and a hidden input + # called _method will carry the intended verb for the server to interpret. # # === Unobtrusive JavaScript # @@ -402,30 +446,59 @@ module ActionView # # === Generic Examples # + # Although the usage and purpose of +field_for+ is similar to +form_for+'s, + # its method signature is slightly different. Like +form_for+, it yields + # a FormBuilder object associated with a particular model object to a block, + # and within the block allows methods to be called on the builder to + # generate fields associated with the model object. Fields may reflect + # a model object in two ways - how they are named (hence how submitted + # values appear within the +params+ hash in the controller) and what + # default values are shown when the form the fields appear in is first + # displayed. In order for both of these features to be specified independently, + # both an object name (represented by either a symbol or string) and the + # object itself can be passed to the method separately - + # # <%= form_for @person do |person_form| %> # First name: <%= person_form.text_field :first_name %> # Last name : <%= person_form.text_field :last_name %> # - # <%= fields_for @person.permission do |permission_fields| %> + # <%= fields_for :permission, @person.permission do |permission_fields| %> # Admin? : <%= permission_fields.check_box :admin %> # <% end %> # # <%= f.submit %> # <% end %> # - # ...or if you have an object that needs to be represented as a different - # parameter, like a Client that acts as a Person: + # In this case, the checkbox field will be represented by an HTML +input+ + # tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted + # value will appear in the controller as <tt>params[:permission][:admin]</tt>. + # If <tt>@person.permission</tt> is an existing record with an attribute + # +admin+, the initial state of the checkbox when first displayed will + # reflect the value of <tt>@person.permission.admin</tt>. + # + # Often this can be simplified by passing just the name of the model + # object to +fields_for+ - # - # <%= fields_for :person, @client do |permission_fields| %> + # <%= fields_for :permission do |permission_fields| %> # Admin?: <%= permission_fields.check_box :admin %> # <% end %> # - # ...or if you don't have an object, just a name of the parameter: + # ...in which case, if <tt>:permission</tt> also happens to be the name of an + # instance variable <tt>@permission</tt>, the initial state of the input + # field will reflect the value of that variable's attribute <tt>@permission.admin</tt>. # - # <%= fields_for :person do |permission_fields| %> + # Alternatively, you can pass just the model object itself (if the first + # argument isn't a string or symbol +fields_for+ will realize that the + # name has been omitted) - + # + # <%= fields_for @person.permission do |permission_fields| %> # Admin?: <%= permission_fields.check_box :admin %> # <% end %> # + # and +fields_for+ will derive the required name of the field from the + # _class_ of the model object, e.g. if <tt>@person.permission</tt>, is + # of class +Permission+, the field will still be named <tt>permission[admin]</tt>. + # # Note: This also works for the methods in FormOptionHelper and # DateHelper that are designed to work with an object as base, like # FormOptionHelper#collection_select and DateHelper#datetime_select. @@ -860,20 +933,20 @@ module ActionView # ==== Examples # # search_field(:user, :name) - # # => <input id="user_name" name="user[name]" size="30" type="search" /> + # # => <input id="user_name" name="user[name]" type="search" /> # search_field(:user, :name, :autosave => false) - # # => <input autosave="false" id="user_name" name="user[name]" size="30" type="search" /> + # # => <input autosave="false" id="user_name" name="user[name]" type="search" /> # search_field(:user, :name, :results => 3) - # # => <input id="user_name" name="user[name]" results="3" size="30" type="search" /> + # # => <input id="user_name" name="user[name]" results="3" type="search" /> # # Assume request.host returns "www.example.com" # search_field(:user, :name, :autosave => true) - # # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" size="30" type="search" /> + # # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" type="search" /> # search_field(:user, :name, :onsearch => true) - # # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" size="30" type="search" /> + # # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" /> # search_field(:user, :name, :autosave => false, :onsearch => true) - # # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" size="30" type="search" /> + # # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" /> # search_field(:user, :name, :autosave => true, :onsearch => true) - # # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" size="30" type="search" /> + # # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" type="search" /> # def search_field(object_name, method, options = {}) Tags::SearchField.new(object_name, method, self, options).render @@ -882,7 +955,7 @@ module ActionView # Returns a text_field of type "tel". # # telephone_field("user", "phone") - # # => <input id="user_phone" name="user[phone]" size="30" type="tel" /> + # # => <input id="user_phone" name="user[phone]" type="tel" /> # def telephone_field(object_name, method, options = {}) Tags::TelField.new(object_name, method, self, options).render @@ -910,7 +983,7 @@ module ActionView # Returns a text_field of type "url". # # url_field("user", "homepage") - # # => <input id="user_homepage" size="30" name="user[homepage]" type="url" /> + # # => <input id="user_homepage" name="user[homepage]" type="url" /> # def url_field(object_name, method, options = {}) Tags::UrlField.new(object_name, method, self, options).render @@ -919,7 +992,7 @@ module ActionView # Returns a text_field of type "email". # # email_field("user", "address") - # # => <input id="user_address" size="30" name="user[address]" type="email" /> + # # => <input id="user_address" name="user[address]" type="email" /> # def email_field(object_name, method, options = {}) Tags::EmailField.new(object_name, method, self, options).render @@ -985,7 +1058,12 @@ module ActionView self end - def initialize(object_name, object, template, options) + def initialize(object_name, object, template, options, block=nil) + if block + ActiveSupport::Deprecation.warn( + "Giving a block to FormBuilder is deprecated and has no effect anymore.") + end + @nested_child_index = {} @object_name, @object, @template, @options = object_name, object, template, options @parent_builder = options[:parent_builder] @@ -1016,7 +1094,7 @@ module ActionView fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options? fields_options[:builder] ||= options[:builder] fields_options[:parent_builder] = self - fields_options[:namespace] = fields_options[:parent_builder].options[:namespace] + fields_options[:namespace] = options[:namespace] case record_name when String, Symbol diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index f73ca220fb..d61c2bbee2 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -153,6 +153,8 @@ module ActionView # form, and parameters extraction gets the last occurrence of any repeated # key in the query string, that works for ordinary forms. # + # In case if you don't want the helper to generate this hidden field you can specify <tt>:include_blank => false</tt> option. + # def select(object, method, choices, options = {}, html_options = {}) Tags::Select.new(object, method, self, choices, options, html_options).render end @@ -578,9 +580,9 @@ module ActionView # b.label(:class => "radio_button") { b.radio_button(:class => "radio_button") } # end # - # There are also two special methods available: <tt>text</tt> and - # <tt>value</tt>, which are the current text and value methods for the - # item being rendered, respectively. You can use them like this: + # There are also three special methods available: <tt>object</tt>, <tt>text</tt> and + # <tt>value</tt>, which are the current item being rendered, its text and value methods, + # respectively. You can use them like this: # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b| # b.label(:"data-value" => b.value) { b.radio_button + b.text } # end @@ -641,9 +643,9 @@ module ActionView # b.label(:class => "check_box") { b.check_box(:class => "check_box") } # end # - # There are also two special methods available: <tt>text</tt> and - # <tt>value</tt>, which are the current text and value methods for the - # item being rendered, respectively. You can use them like this: + # There are also three special methods available: <tt>object</tt>, <tt>text</tt> and + # <tt>value</tt>, which are the current item being rendered, its text and value methods, + # respectively. You can use them like this: # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b| # b.label(:"data-value" => b.value) { b.check_box + b.text } # end diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 2cf1c9055c..e403d6cf5e 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -2,6 +2,7 @@ require 'cgi' require 'action_view/helpers/tag_helper' require 'active_support/core_ext/object/blank' require 'active_support/core_ext/string/output_safety' +require 'active_support/core_ext/module/attribute_accessors' module ActionView # = Action View Form Tag Helpers @@ -17,6 +18,9 @@ module ActionView include UrlHelper include TextHelper + mattr_accessor :embed_authenticity_token_in_remote_forms + self.embed_authenticity_token_in_remote_forms = false + # Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like # ActionController::Base#url_for. The method for the form defaults to POST. # @@ -27,7 +31,11 @@ module ActionView # is added to simulate the verb over post. # * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to # pass custom authenticity token string, or to not add authenticity_token field at all - # (by passing <tt>false</tt>). + # (by passing <tt>false</tt>). Remote forms may omit the embedded authenticity token + # by setting <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>. + # This is helpful when you're fragment-caching the form. Remote forms get the + # authenticity from the <tt>meta</tt> tag, so embedding is unnecessary unless you + # support browsers without JavaScript. # * A list of parameters to feed to the URL the form will be posted to. # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the # submit behavior. By default this behavior is an ajax submit. @@ -93,7 +101,7 @@ module ActionView # # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option> # # <option>Green</option><option>Blue</option></select> # - # select_tag "locations", "<option>Home</option><option selected="selected">Work</option><option>Out</option>".html_safe + # select_tag "locations", "<option>Home</option><option selected='selected'>Work</option><option>Out</option>".html_safe # # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option> # # <option>Out</option></select> # @@ -525,10 +533,9 @@ module ActionView # <% end %> # # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset> def field_set_tag(legend = nil, options = nil, &block) - content = capture(&block) output = tag(:fieldset, options, true) output.safe_concat(content_tag(:legend, legend)) unless legend.blank? - output.concat(content) + output.concat(capture(&block)) if block_given? output.safe_concat("</fieldset>") end @@ -617,8 +624,19 @@ module ActionView # responsibility of the caller to escape all the values. html_options["action"] = url_for(url_for_options) html_options["accept-charset"] = "UTF-8" + html_options["data-remote"] = true if html_options.delete("remote") - html_options["authenticity_token"] = html_options.delete("authenticity_token") if html_options.has_key?("authenticity_token") + + if html_options["data-remote"] && + !embed_authenticity_token_in_remote_forms && + html_options["authenticity_token"].blank? + # The authenticity token is taken from the meta tag in this case + html_options["authenticity_token"] = false + elsif html_options["authenticity_token"] == true + # Include the default authenticity_token, which is only generated when its set to nil, + # but we needed the true value to override the default of no authenticity_token on data-remote. + html_options["authenticity_token"] = nil + end end end diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb index ac9e530f01..d88f5babb9 100644 --- a/actionpack/lib/action_view/helpers/javascript_helper.rb +++ b/actionpack/lib/action_view/helpers/javascript_helper.rb @@ -14,6 +14,8 @@ module ActionView } JS_ESCAPE_MAP["\342\200\250".force_encoding('UTF-8').encode!] = '
' + JS_ESCAPE_MAP["\342\200\251".force_encoding('UTF-8').encode!] = '
' + # Escapes carriage returns and single and double quotes for JavaScript segments. # @@ -22,7 +24,7 @@ module ActionView # $('some_element').replaceWith('<%=j render 'some/element_template' %>'); def escape_javascript(javascript) if javascript - result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] } + result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] } javascript.html_safe? ? result.html_safe : result else '' diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb index b0860f87c4..485a9357be 100644 --- a/actionpack/lib/action_view/helpers/number_helper.rb +++ b/actionpack/lib/action_view/helpers/number_helper.rb @@ -292,6 +292,7 @@ module ActionView precision = precision > 0 ? precision : 0 #don't let it be negative else rounded_number = BigDecimal.new(number.to_s).round(precision).to_f + rounded_number = rounded_number.zero? ? rounded_number.abs : rounded_number #prevent showing negative zeros end formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options) if strip_insignificant_zeros diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index ecd26891d6..71be2955a8 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -17,6 +17,10 @@ module ActionView autofocus novalidate formnovalidate open pubdate).to_set BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym }) + PRE_CONTENT_STRINGS = { + :textarea => "\n" + } + # Returns an empty HTML tag of type +name+ which by default is XHTML # compliant. Set +open+ to true to create an open tag compatible # with HTML 4.0 and below. Add HTML attributes by passing an attributes @@ -126,7 +130,7 @@ module ActionView def content_tag_string(name, content, options, escape = true) tag_options = tag_options(options, escape) if options content = ERB::Util.h(content) if escape - "<#{name}#{tag_options}>#{content}</#{name}>".html_safe + "<#{name}#{tag_options}>#{PRE_CONTENT_STRINGS[name.to_sym]}#{content}</#{name}>".html_safe end def tag_options(options, escape = true) diff --git a/actionpack/lib/action_view/helpers/tags/base.rb b/actionpack/lib/action_view/helpers/tags/base.rb index c9c891daa1..7c2f12d8e7 100644 --- a/actionpack/lib/action_view/helpers/tags/base.rb +++ b/actionpack/lib/action_view/helpers/tags/base.rb @@ -5,8 +5,6 @@ module ActionView include Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper include FormOptionsHelper - DEFAULT_FIELD_OPTIONS = { "size" => 30 } - attr_reader :object def initialize(object_name, method_name, template_object, options = {}) @@ -124,7 +122,8 @@ module ActionView html_options = html_options.stringify_keys add_default_name_and_id(html_options) select = content_tag("select", add_options(option_tags, options, value(object)), html_options) - if html_options["multiple"] + + if html_options["multiple"] && options.fetch(:include_hidden) { true } tag("input", :disabled => html_options["disabled"], :name => html_options["name"], :type => "hidden", :value => "") + select else select @@ -133,12 +132,11 @@ module ActionView def add_options(option_tags, options, value = nil) if options[:include_blank] - include_blank = options[:include_blank] if options[:include_blank].kind_of?(String) - option_tags = content_tag(:option, include_blank, :value => '').safe_concat("\n").safe_concat(option_tags) + 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 => '').safe_concat("\n").safe_concat(option_tags) + option_tags = content_tag('option', prompt, :value => '') + "\n" + option_tags end option_tags end diff --git a/actionpack/lib/action_view/helpers/tags/check_box.rb b/actionpack/lib/action_view/helpers/tags/check_box.rb index 579cdb9fc9..1a4aebb936 100644 --- a/actionpack/lib/action_view/helpers/tags/check_box.rb +++ b/actionpack/lib/action_view/helpers/tags/check_box.rb @@ -25,9 +25,15 @@ module ActionView add_default_name_and_id(options) end - hidden = hidden_field_for_checkbox(options) + include_hidden = options.delete("include_hidden") { true } checkbox = tag("input", options) - hidden + checkbox + + if include_hidden + hidden = hidden_field_for_checkbox(options) + hidden + checkbox + else + checkbox + end end private diff --git a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb index 6f950e552a..6a1479069f 100644 --- a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb +++ b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb @@ -59,6 +59,7 @@ module ActionView end end + html_options[:object] = @object html_options end diff --git a/actionpack/lib/action_view/helpers/tags/label.rb b/actionpack/lib/action_view/helpers/tags/label.rb index 1bd71c2778..16135fcd5a 100644 --- a/actionpack/lib/action_view/helpers/tags/label.rb +++ b/actionpack/lib/action_view/helpers/tags/label.rb @@ -3,16 +3,16 @@ module ActionView module Tags class Label < Base #:nodoc: def initialize(object_name, method_name, template_object, content_or_options = nil, options = nil) + options ||= {} + content_is_options = content_or_options.is_a?(Hash) if content_is_options - options = content_or_options + options.merge! content_or_options @content = nil else @content = content_or_options end - options ||= {} - super(object_name, method_name, template_object, options) end @@ -33,7 +33,7 @@ module ActionView options["for"] = name_and_id["id"] unless options.key?("for") if block_given? - @template_object.label_tag(name_and_id["id"], options, &block) + content = @template_object.capture(&block) else content = if @content.blank? @object_name.gsub!(/\[(.*)_attributes\]\[\d\]/, '.\1') @@ -55,9 +55,9 @@ module ActionView end content ||= @method_name.humanize - - label_tag(name_and_id["id"], content, options) end + + label_tag(name_and_id["id"], content, options) end end end diff --git a/actionpack/lib/action_view/helpers/tags/text_area.rb b/actionpack/lib/action_view/helpers/tags/text_area.rb index a7db8eb437..f74652c5e7 100644 --- a/actionpack/lib/action_view/helpers/tags/text_area.rb +++ b/actionpack/lib/action_view/helpers/tags/text_area.rb @@ -2,17 +2,15 @@ module ActionView module Helpers module Tags class TextArea < Base #:nodoc: - DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 20 } - def render - options = DEFAULT_TEXT_AREA_OPTIONS.merge(@options.stringify_keys) + options = @options.stringify_keys add_default_name_and_id(options) if size = options.delete("size") options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split) end - content_tag("textarea", ERB::Util.html_escape(options.delete('value') || value_before_type_cast(object)), options) + content_tag("textarea", options.delete('value') || value_before_type_cast(object), options) end end end diff --git a/actionpack/lib/action_view/helpers/tags/text_field.rb b/actionpack/lib/action_view/helpers/tags/text_field.rb index ce5182d20f..024a1a8af2 100644 --- a/actionpack/lib/action_view/helpers/tags/text_field.rb +++ b/actionpack/lib/action_view/helpers/tags/text_field.rb @@ -4,8 +4,7 @@ module ActionView class TextField < Base #:nodoc: def render options = @options.stringify_keys - options["size"] = options["maxlength"] || DEFAULT_FIELD_OPTIONS["size"] unless options.key?("size") - options = DEFAULT_FIELD_OPTIONS.merge(options) + options["size"] = options["maxlength"] unless options.key?("size") options["type"] ||= field_type options["value"] = options.fetch("value"){ value_before_type_cast(object) } unless field_type == "file" options["value"] &&= ERB::Util.html_escape(options["value"]) diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 8d7417809b..4a641fada3 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -23,20 +23,25 @@ module ActionView include ActionDispatch::Routing::UrlFor include TagHelper - def _routes_context - controller - end + # We need to override url_optoins, _routes_context + # and optimize_routes_generation? to consider the controller. - # Need to map default url options to controller one. - # def default_url_options(*args) #:nodoc: - # controller.send(:default_url_options, *args) - # end - # - def url_options + def url_options #:nodoc: return super unless controller.respond_to?(:url_options) controller.url_options end + def _routes_context #:nodoc: + controller + end + protected :_routes_context + + def optimize_routes_generation? #:nodoc: + controller.respond_to?(:optimize_routes_generation?) ? + controller.optimize_routes_generation? : super + end + protected :optimize_routes_generation? + # Returns the URL for the set of +options+ provided. This takes the # same options as +url_for+ in Action Controller (see the # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default @@ -55,7 +60,7 @@ module ActionView # # ==== Relying on named routes # - # Passing a record (like an Active Record or Active Resource) instead of a Hash as the options parameter will + # Passing a record (like an Active Record) instead of a Hash as the options parameter will # trigger the named route for that record. The lookup will happen on the name of the class. So passing a # Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route). @@ -329,7 +334,7 @@ module ActionView remote = html_options.delete('remote') method = html_options.delete('method').to_s - method_tag = %w{patch put delete}.include?(method) ? method_tag(method) : "" + method_tag = %w{patch put delete}.include?(method) ? method_tag(method) : ''.html_safe form_method = method == 'get' ? 'get' : 'post' form_options = html_options.delete('form') || {} @@ -342,7 +347,8 @@ module ActionView html_options = convert_options_to_data_attributes(options, html_options) html_options.merge!("type" => "submit", "value" => name || url) - "#{tag(:form, form_options, true)}<div>#{method_tag}#{tag("input", html_options)}#{request_token_tag}</div></form>".html_safe + inner_tags = method_tag.safe_concat tag('input', html_options).safe_concat request_token_tag + content_tag('form', content_tag('div', inner_tags), form_options) end diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb index 43371a1c49..9f5e3be454 100644 --- a/actionpack/lib/action_view/railtie.rb +++ b/actionpack/lib/action_view/railtie.rb @@ -7,6 +7,14 @@ module ActionView config.action_view = ActiveSupport::OrderedOptions.new config.action_view.stylesheet_expansions = {} config.action_view.javascript_expansions = { :defaults => %w(jquery jquery_ujs) } + config.action_view.embed_authenticity_token_in_remote_forms = false + + initializer "action_view.embed_authenticity_token_in_remote_forms" do |app| + ActiveSupport.on_load(:action_view) do + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = + app.config.action_view.delete(:embed_authenticity_token_in_remote_forms) + end + end initializer "action_view.logger" do ActiveSupport.on_load(:action_view) { self.logger ||= Rails.logger } diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb index 3033294883..8b53867aea 100644 --- a/actionpack/lib/action_view/renderer/partial_renderer.rb +++ b/actionpack/lib/action_view/renderer/partial_renderer.rb @@ -32,7 +32,7 @@ module ActionView # # <%= render :partial => "account", :object => @buyer %> # - # would provide the +@buyer+ object to the partial, available under the local variable +account+ and is + # would provide the <tt>@buyer</tt> object to the partial, available under the local variable +account+ and is # equivalent to: # # <%= render :partial => "account", :locals => { :account => @buyer } %> @@ -158,6 +158,43 @@ module ActionView # Name: <%= user.name %> # </div> # + # If a collection is given, the layout will be rendered once for each item in the collection. Just think + # these two snippets have the same output: + # + # <%# app/views/users/_user.html.erb %> + # Name: <%= user.name %> + # + # <%# app/views/users/index.html.erb %> + # <%# This does not use layouts %> + # <ul> + # <% users.each do |user| -%> + # <li> + # <%= render :partial => "user", :locals => { :user => user } %> + # </li> + # <% end -%> + # </ul> + # + # <%# app/views/users/_li_layout.html.erb %> + # <li> + # <%= yield %> + # </li> + # + # <%# app/views/users/index.html.erb %> + # <ul> + # <%= render :partial => "user", :layout => "li_layout", :collection => users %> + # </ul> + # + # Given two users whose names are Alice and Bob, these snippets return: + # + # <ul> + # <li> + # Name: Alice + # </li> + # <li> + # Name: Bob + # </li> + # </ul> + # # You can also apply a layout to a block within any template: # # <%# app/views/users/_chief.html.erb &> @@ -208,18 +245,25 @@ module ActionView # <%- end -%> # <% end %> class PartialRenderer < AbstractRenderer - PARTIAL_NAMES = Hash.new { |h,k| h[k] = {} } + PREFIXED_PARTIAL_NAMES = Hash.new { |h,k| h[k] = {} } def initialize(*) super @context_prefix = @lookup_context.prefixes.first - @partial_names = PARTIAL_NAMES[@context_prefix] end def render(context, options, block) setup(context, options, block) identifier = (@template = find_partial) ? @template.identifier : @path + @lookup_context.rendered_format ||= begin + if @template && @template.formats.present? + @template.formats.first + else + formats.first + end + end + if @collection instrument(:collection, :identifier => identifier || "collection", :count => @collection.size) do render_collection @@ -238,7 +282,14 @@ module ActionView spacer = find_template(@options[:spacer_template]).render(@view, @locals) end + if layout = @options[:layout] + layout = find_template(layout) + end + result = @template ? collection_with_template : collection_without_template + + result.map!{|content| layout.render(@view, @locals) { content } } if layout + result.join(spacer).html_safe end @@ -340,9 +391,10 @@ module ActionView locals[as] = object segments << template.render(@view, locals) end - + segments end + def collection_without_template segments, locals, collection_data = [], @locals, @collection_data @@ -370,7 +422,15 @@ module ActionView raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.") end - @partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) + if @view.prefix_partial_path_with_controller_namespace + prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) + else + path + end + end + + def prefixed_partial_names + @prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix] end def merge_prefix_into_object_path(prefix, object_path) diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb index 20f75fba45..ae923de24e 100644 --- a/actionpack/lib/action_view/renderer/template_renderer.rb +++ b/actionpack/lib/action_view/renderer/template_renderer.rb @@ -6,8 +6,13 @@ module ActionView @view = context @details = extract_details(options) template = determine_template(options) - @lookup_context.rendered_format ||= template.formats.first - @lookup_context.formats = template.formats + context = @lookup_context + + unless context.rendered_format + context.formats = template.formats unless template.formats.empty? + context.rendered_format = context.formats.first + end + render_template(template, options[:layout], options[:locals]) end diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb index 7fa86866a7..8ea2e5bfe4 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -176,7 +176,7 @@ module ActionView end end - # A resolver that loads files from the filesystem. It allows to set your own + # A resolver that loads files from the filesystem. It allows setting your own # resolving pattern. Such pattern can be a glob string supported by some variables. # # ==== Examples @@ -192,7 +192,7 @@ module ActionView # # FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{.:handlers,}") # - # If you don't specify pattern then the default will be used. + # If you don't specify a pattern then the default will be used. # # In order to use any of the customized resolvers above in a Rails application, you just need # to configure ActionController::Base.view_paths in an initializer, for example: @@ -204,10 +204,10 @@ module ActionView # # ==== Pattern format and variables # - # Pattern have to be a valid glob string, and it allows you to use the + # Pattern has to be a valid glob string, and it allows you to use the # following variables: # - # * <tt>:prefix</tt> - usualy the controller path + # * <tt>:prefix</tt> - usually the controller path # * <tt>:action</tt> - name of the action # * <tt>:locale</tt> - possible locale versions # * <tt>:formats</tt> - possible request formats (for example html, json, xml...) diff --git a/actionpack/lib/sprockets/assets.rake b/actionpack/lib/sprockets/assets.rake deleted file mode 100644 index 2e92fe416b..0000000000 --- a/actionpack/lib/sprockets/assets.rake +++ /dev/null @@ -1,105 +0,0 @@ -require "fileutils" - -namespace :assets do - def ruby_rake_task(task, fork = true) - env = ENV['RAILS_ENV'] || 'production' - groups = ENV['RAILS_GROUPS'] || 'assets' - args = [$0, task,"RAILS_ENV=#{env}","RAILS_GROUPS=#{groups}"] - args << "--trace" if Rake.application.options.trace - if $0 =~ /rake\.bat\Z/i - Kernel.exec $0, *args - else - fork ? ruby(*args) : Kernel.exec(FileUtils::RUBY, *args) - end - end - - # We are currently running with no explicit bundler group - # and/or no explicit environment - we have to reinvoke rake to - # execute this task. - def invoke_or_reboot_rake_task(task) - if ENV['RAILS_GROUPS'].to_s.empty? || ENV['RAILS_ENV'].to_s.empty? - ruby_rake_task task - else - Rake::Task[task].invoke - end - end - - desc "Compile all the assets named in config.assets.precompile" - task :precompile do - invoke_or_reboot_rake_task "assets:precompile:all" - end - - namespace :precompile do - def internal_precompile(digest=nil) - unless Rails.application.config.assets.enabled - warn "Cannot precompile assets if sprockets is disabled. Please set config.assets.enabled to true" - exit - end - - # Ensure that action view is loaded and the appropriate - # sprockets hooks get executed - _ = ActionView::Base - - config = Rails.application.config - config.assets.compile = true - config.assets.digest = digest unless digest.nil? - config.assets.digests = {} - - env = Rails.application.assets - target = File.join(Rails.public_path, config.assets.prefix) - compiler = Sprockets::StaticCompiler.new(env, - target, - config.assets.precompile, - :manifest_path => config.assets.manifest, - :digest => config.assets.digest, - :manifest => digest.nil?) - compiler.compile - end - - task :all do - Rake::Task["assets:precompile:primary"].invoke - # We need to reinvoke in order to run the secondary digestless - # asset compilation run - a fresh Sprockets environment is - # required in order to compile digestless assets as the - # environment has already cached the assets on the primary - # run. - ruby_rake_task("assets:precompile:nondigest", false) if Rails.application.config.assets.digest - end - - task :primary => ["assets:cache:clean"] do - internal_precompile - end - - task :nondigest => ["assets:cache:clean"] do - internal_precompile(false) - end - end - - desc "Remove compiled assets" - task :clean do - invoke_or_reboot_rake_task "assets:clean:all" - end - - namespace :clean do - task :all => ["assets:cache:clean"] do - config = Rails.application.config - public_asset_path = File.join(Rails.public_path, config.assets.prefix) - rm_rf public_asset_path, :secure => true - end - end - - namespace :cache do - task :clean => ["assets:environment"] do - Rails.application.assets.cache.clear - end - end - - task :environment do - if Rails.application.config.assets.initialize_on_precompile - Rake::Task["environment"].invoke - else - Rails.application.initialize!(:assets) - Sprockets::Bootstrap.new(Rails.application).run - end - end -end diff --git a/actionpack/lib/sprockets/bootstrap.rb b/actionpack/lib/sprockets/bootstrap.rb deleted file mode 100644 index 395b264fe7..0000000000 --- a/actionpack/lib/sprockets/bootstrap.rb +++ /dev/null @@ -1,37 +0,0 @@ -module Sprockets - class Bootstrap - def initialize(app) - @app = app - end - - # TODO: Get rid of config.assets.enabled - def run - app, config = @app, @app.config - return unless app.assets - - config.assets.paths.each { |path| app.assets.append_path(path) } - - if config.assets.compress - # temporarily hardcode default JS compressor to uglify. Soon, it will work - # the same as SCSS, where a default plugin sets the default. - unless config.assets.js_compressor == false - app.assets.js_compressor = LazyCompressor.new { Sprockets::Compressors.registered_js_compressor(config.assets.js_compressor || :uglifier) } - end - - unless config.assets.css_compressor == false - app.assets.css_compressor = LazyCompressor.new { Sprockets::Compressors.registered_css_compressor(config.assets.css_compressor) } - end - end - - if config.assets.compile - app.routes.prepend do - mount app.assets => config.assets.prefix - end - end - - if config.assets.digest - app.assets = app.assets.index - end - end - end -end diff --git a/actionpack/lib/sprockets/compressors.rb b/actionpack/lib/sprockets/compressors.rb deleted file mode 100644 index 8b728d6570..0000000000 --- a/actionpack/lib/sprockets/compressors.rb +++ /dev/null @@ -1,85 +0,0 @@ -module Sprockets - module Compressors - extend self - - @@css_compressors = {} - @@js_compressors = {} - @@default_css_compressor = nil - @@default_js_compressor = nil - - def register_css_compressor(name, klass, options = {}) - @@default_css_compressor = name.to_sym if options[:default] || @@default_css_compressor.nil? - @@css_compressors[name.to_sym] = { :klass => klass.to_s, :require => options[:require] } - end - - def register_js_compressor(name, klass, options = {}) - @@default_js_compressor = name.to_sym if options[:default] || @@default_js_compressor.nil? - @@js_compressors[name.to_sym] = { :klass => klass.to_s, :require => options[:require] } - end - - def registered_css_compressor(name) - find_registered_compressor name, @@css_compressors, @@default_css_compressor - end - - def registered_js_compressor(name) - find_registered_compressor name, @@js_compressors, @@default_js_compressor - end - - # The default compressors must be registered in default plugins (ex. Sass-Rails) - register_css_compressor(:scss, 'Sass::Rails::Compressor', :require => 'sass/rails/compressor', :default => true) - register_js_compressor(:uglifier, 'Uglifier', :require => 'uglifier', :default => true) - - # Automaticaly register some compressors - register_css_compressor(:yui, 'YUI::CssCompressor', :require => 'yui/compressor') - register_js_compressor(:closure, 'Closure::Compiler', :require => 'closure-compiler') - register_js_compressor(:yui, 'YUI::JavaScriptCompressor', :require => 'yui/compressor') - - private - - def find_registered_compressor(name, compressors_hash, default_compressor_name) - if name.respond_to?(:to_sym) - compressor = compressors_hash[name.to_sym] || compressors_hash[default_compressor_name] - require compressor[:require] if compressor[:require] - compressor[:klass].constantize.new - else - name - end - end - end - - # An asset compressor which does nothing. - # - # This compressor simply returns the asset as-is, without any compression - # whatsoever. It is useful in development mode, when compression isn't - # needed but using the same asset pipeline as production is desired. - class NullCompressor #:nodoc: - def compress(content) - content - end - end - - # An asset compressor which only initializes the underlying compression - # engine when needed. - # - # This postpones the initialization of the compressor until - # <code>#compress</code> is called the first time. - class LazyCompressor #:nodoc: - # Initializes a new LazyCompressor. - # - # The block should return a compressor when called, i.e. an object - # which responds to <code>#compress</code>. - def initialize(&block) - @block = block - end - - def compress(content) - compressor.compress(content) - end - - private - - def compressor - @compressor ||= (@block.call || NullCompressor.new) - end - end -end diff --git a/actionpack/lib/sprockets/helpers.rb b/actionpack/lib/sprockets/helpers.rb deleted file mode 100644 index fee48386e0..0000000000 --- a/actionpack/lib/sprockets/helpers.rb +++ /dev/null @@ -1,6 +0,0 @@ -module Sprockets - module Helpers - autoload :RailsHelper, "sprockets/helpers/rails_helper" - autoload :IsolatedHelper, "sprockets/helpers/isolated_helper" - end -end diff --git a/actionpack/lib/sprockets/helpers/isolated_helper.rb b/actionpack/lib/sprockets/helpers/isolated_helper.rb deleted file mode 100644 index 3adb928c45..0000000000 --- a/actionpack/lib/sprockets/helpers/isolated_helper.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Sprockets - module Helpers - module IsolatedHelper - def controller - nil - end - - def config - Rails.application.config.action_controller - end - end - end -end diff --git a/actionpack/lib/sprockets/helpers/rails_helper.rb b/actionpack/lib/sprockets/helpers/rails_helper.rb deleted file mode 100644 index 839ec7635f..0000000000 --- a/actionpack/lib/sprockets/helpers/rails_helper.rb +++ /dev/null @@ -1,167 +0,0 @@ -require "action_view" - -module Sprockets - module Helpers - module RailsHelper - extend ActiveSupport::Concern - include ActionView::Helpers::AssetTagHelper - - def asset_paths - @asset_paths ||= begin - paths = RailsHelper::AssetPaths.new(config, controller) - paths.asset_environment = asset_environment - paths.asset_digests = asset_digests - paths.compile_assets = compile_assets? - paths.digest_assets = digest_assets? - paths - end - end - - def javascript_include_tag(*sources) - options = sources.extract_options! - debug = options.delete(:debug) { debug_assets? } - body = options.delete(:body) { false } - digest = options.delete(:digest) { digest_assets? } - - sources.collect do |source| - if debug && asset = asset_paths.asset_for(source, 'js') - asset.to_a.map { |dep| - super(dep.pathname.to_s, { :src => path_to_asset(dep, :ext => 'js', :body => true, :digest => digest) }.merge!(options)) - } - else - super(source.to_s, { :src => path_to_asset(source, :ext => 'js', :body => body, :digest => digest) }.merge!(options)) - end - end.join("\n").html_safe - end - - def stylesheet_link_tag(*sources) - options = sources.extract_options! - debug = options.delete(:debug) { debug_assets? } - body = options.delete(:body) { false } - digest = options.delete(:digest) { digest_assets? } - - sources.collect do |source| - if debug && asset = asset_paths.asset_for(source, 'css') - asset.to_a.map { |dep| - super(dep.pathname.to_s, { :href => path_to_asset(dep, :ext => 'css', :body => true, :protocol => :request, :digest => digest) }.merge!(options)) - } - else - super(source.to_s, { :href => path_to_asset(source, :ext => 'css', :body => body, :protocol => :request, :digest => digest) }.merge!(options)) - end - end.join("\n").html_safe - end - - def asset_path(source, options = {}) - source = source.logical_path if source.respond_to?(:logical_path) - path = asset_paths.compute_public_path(source, asset_prefix, options.merge(:body => true)) - options[:body] ? "#{path}?body=1" : path - end - alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with an asset_path named route - - def image_path(source) - path_to_asset(source) - end - alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route - - def font_path(source) - path_to_asset(source) - end - alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route - - def javascript_path(source) - path_to_asset(source, :ext => 'js') - end - alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with an javascript_path named route - - def stylesheet_path(source) - path_to_asset(source, :ext => 'css') - end - alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with an stylesheet_path named route - - private - def debug_assets? - compile_assets? && (Rails.application.config.assets.debug || params[:debug_assets]) - rescue NoMethodError - false - end - - # Override to specify an alternative prefix for asset path generation. - # When combined with a custom +asset_environment+, this can be used to - # implement themes that can take advantage of the asset pipeline. - # - # If you only want to change where the assets are mounted, refer to - # +config.assets.prefix+ instead. - def asset_prefix - Rails.application.config.assets.prefix - end - - def asset_digests - Rails.application.config.assets.digests - end - - def compile_assets? - Rails.application.config.assets.compile - end - - def digest_assets? - Rails.application.config.assets.digest - end - - # Override to specify an alternative asset environment for asset - # path generation. The environment should already have been mounted - # at the prefix returned by +asset_prefix+. - def asset_environment - Rails.application.assets - end - - class AssetPaths < ::ActionView::AssetPaths #:nodoc: - attr_accessor :asset_environment, :asset_prefix, :asset_digests, :compile_assets, :digest_assets - - class AssetNotPrecompiledError < StandardError; end - - def asset_for(source, ext) - source = source.to_s - return nil if is_uri?(source) - source = rewrite_extension(source, nil, ext) - asset_environment[source] - rescue Sprockets::FileOutsidePaths - nil - end - - def digest_for(logical_path) - if digest_assets && asset_digests && (digest = asset_digests[logical_path]) - return digest - end - - if compile_assets - if digest_assets && asset = asset_environment[logical_path] - return asset.digest_path - end - return logical_path - else - raise AssetNotPrecompiledError.new("#{logical_path} isn't precompiled") - end - end - - def rewrite_asset_path(source, dir, options = {}) - if source[0] == ?/ - source - else - source = digest_for(source) unless options[:digest] == false - source = File.join(dir, source) - source = "/#{source}" unless source =~ /^\// - source - end - end - - def rewrite_extension(source, dir, ext) - if ext && File.extname(source) != ".#{ext}" - "#{source}.#{ext}" - else - source - end - end - end - end - end -end diff --git a/actionpack/lib/sprockets/railtie.rb b/actionpack/lib/sprockets/railtie.rb deleted file mode 100644 index 2bc482a39d..0000000000 --- a/actionpack/lib/sprockets/railtie.rb +++ /dev/null @@ -1,62 +0,0 @@ -require "action_controller/railtie" - -module Sprockets - autoload :Bootstrap, "sprockets/bootstrap" - autoload :Helpers, "sprockets/helpers" - autoload :Compressors, "sprockets/compressors" - autoload :LazyCompressor, "sprockets/compressors" - autoload :NullCompressor, "sprockets/compressors" - autoload :StaticCompiler, "sprockets/static_compiler" - - # TODO: Get rid of config.assets.enabled - class Railtie < ::Rails::Railtie - rake_tasks do - load "sprockets/assets.rake" - end - - initializer "sprockets.environment", :group => :all do |app| - config = app.config - next unless config.assets.enabled - - require 'sprockets' - - app.assets = Sprockets::Environment.new(app.root.to_s) do |env| - env.version = ::Rails.env + "-#{config.assets.version}" - - if config.assets.logger != false - env.logger = config.assets.logger || ::Rails.logger - end - - if config.assets.cache_store != false - env.cache = ActiveSupport::Cache.lookup_store(config.assets.cache_store) || ::Rails.cache - end - end - - if config.assets.manifest - path = File.join(config.assets.manifest, "manifest.yml") - else - path = File.join(Rails.public_path, config.assets.prefix, "manifest.yml") - end - - if File.exist?(path) - config.assets.digests = YAML.load_file(path) - end - - ActiveSupport.on_load(:action_view) do - include ::Sprockets::Helpers::RailsHelper - app.assets.context_class.instance_eval do - include ::Sprockets::Helpers::IsolatedHelper - include ::Sprockets::Helpers::RailsHelper - end - end - end - - # We need to configure this after initialization to ensure we collect - # paths from all engines. This hook is invoked exactly before routes - # are compiled, and so that other Railties have an opportunity to - # register compressors. - config.after_initialize do |app| - Sprockets::Bootstrap.new(app).run - end - end -end diff --git a/actionpack/lib/sprockets/static_compiler.rb b/actionpack/lib/sprockets/static_compiler.rb deleted file mode 100644 index 9bbb464474..0000000000 --- a/actionpack/lib/sprockets/static_compiler.rb +++ /dev/null @@ -1,62 +0,0 @@ -require 'fileutils' - -module Sprockets - class StaticCompiler - attr_accessor :env, :target, :paths - - def initialize(env, target, paths, options = {}) - @env = env - @target = target - @paths = paths - @digest = options.fetch(:digest, true) - @manifest = options.fetch(:manifest, true) - @manifest_path = options.delete(:manifest_path) || target - @zip_files = options.delete(:zip_files) || /\.(?:css|html|js|svg|txt|xml)$/ - end - - def compile - manifest = {} - env.each_logical_path do |logical_path| - next unless compile_path?(logical_path) - if asset = env.find_asset(logical_path) - manifest[logical_path] = write_asset(asset) - end - end - write_manifest(manifest) if @manifest - end - - def write_manifest(manifest) - FileUtils.mkdir_p(@manifest_path) - File.open("#{@manifest_path}/manifest.yml", 'wb') do |f| - YAML.dump(manifest, f) - end - end - - def write_asset(asset) - path_for(asset).tap do |path| - filename = File.join(target, path) - FileUtils.mkdir_p File.dirname(filename) - asset.write_to(filename) - asset.write_to("#{filename}.gz") if filename.to_s =~ @zip_files - end - end - - def compile_path?(logical_path) - paths.each do |path| - case path - when Regexp - return true if path.match(logical_path) - when Proc - return true if path.call(logical_path) - else - return true if File.fnmatch(path.to_s, logical_path) - end - end - false - end - - def path_for(asset) - @digest ? asset.digest_path : asset.logical_path - end - end -end diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb index bf068aedcd..62f82a4c7a 100644 --- a/actionpack/test/abstract/abstract_controller_test.rb +++ b/actionpack/test/abstract/abstract_controller_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'set' module AbstractController module Testing @@ -28,7 +29,7 @@ module AbstractController # Test Render mixin # ==== class RenderingController < AbstractController::Base - include ::AbstractController::Rendering + include AbstractController::Rendering def _prefixes [] @@ -152,7 +153,7 @@ module AbstractController # ==== # self._layout is used when defined class WithLayouts < PrefixedViews - include Layouts + include AbstractController::Layouts private def self.layout(formats) @@ -254,7 +255,7 @@ module AbstractController class TestActionMethodsReloading < ActiveSupport::TestCase test "action_methods should be reloaded after defining a new method" do - assert_equal ["index"], Me6.action_methods + assert_equal Set.new(["index"]), Me6.action_methods end end diff --git a/actionpack/test/abstract/collector_test.rb b/actionpack/test/abstract/collector_test.rb index 2ebcebbbb7..c14d24905b 100644 --- a/actionpack/test/abstract/collector_test.rb +++ b/actionpack/test/abstract/collector_test.rb @@ -3,7 +3,7 @@ require 'abstract_unit' module AbstractController module Testing class MyCollector - include Collector + include AbstractController::Collector attr_accessor :responses def initialize @@ -54,4 +54,4 @@ module AbstractController end end end -end
\ No newline at end of file +end diff --git a/actionpack/test/abstract/helper_test.rb b/actionpack/test/abstract/helper_test.rb index b28a5b5afb..9a7445de7b 100644 --- a/actionpack/test/abstract/helper_test.rb +++ b/actionpack/test/abstract/helper_test.rb @@ -7,7 +7,7 @@ module AbstractController class ControllerWithHelpers < AbstractController::Base include AbstractController::Rendering - include Helpers + include AbstractController::Helpers def with_module render :inline => "Module <%= included_method %>" @@ -44,7 +44,7 @@ module AbstractController class AbstractHelpersBlock < ControllerWithHelpers helper do - include ::AbstractController::Testing::HelperyTest + include AbstractController::Testing::HelperyTest end end diff --git a/actionpack/test/abstract/layouts_test.rb b/actionpack/test/abstract/layouts_test.rb index fc25718d9e..558a45b87f 100644 --- a/actionpack/test/abstract/layouts_test.rb +++ b/actionpack/test/abstract/layouts_test.rb @@ -14,7 +14,10 @@ module AbstractControllerTests "layouts/overwrite.erb" => "Overwrite <%= yield %>", "layouts/with_false_layout.erb" => "False Layout <%= yield %>", "abstract_controller_tests/layouts/with_string_implied_child.erb" => - "With Implied <%= yield %>" + "With Implied <%= yield %>", + "abstract_controller_tests/layouts/with_grand_child_of_implied.erb" => + "With Grand Child <%= yield %>" + )] end @@ -64,6 +67,10 @@ module AbstractControllerTests class WithChildOfImplied < WithStringImpliedChild end + class WithGrandChildOfImplied < WithStringImpliedChild + layout nil + end + class WithProc < Base layout proc { |c| "overwrite" } @@ -72,6 +79,27 @@ module AbstractControllerTests end end + class WithZeroArityProc < Base + layout proc { "overwrite" } + + def index + render :template => ActionView::Template::Text.new("Hello zero arity proc!") + end + end + + class WithProcInContextOfInstance < Base + def an_instance_method; end + + layout proc { + break unless respond_to? :an_instance_method + "overwrite" + } + + def index + render :template => ActionView::Template::Text.new("Hello again zero arity proc!") + end + end + class WithSymbol < Base layout :hello @@ -221,6 +249,18 @@ module AbstractControllerTests assert_equal "Overwrite Hello proc!", controller.response_body end + test "when layout is specified as a proc without parameters it works just the same" do + controller = WithZeroArityProc.new + controller.process(:index) + assert_equal "Overwrite Hello zero arity proc!", controller.response_body + end + + test "when layout is specified as a proc without parameters the block is evaluated in the context of an instance" do + controller = WithProcInContextOfInstance.new + controller.process(:index) + assert_equal "Overwrite Hello again zero arity proc!", controller.response_body + end + test "when layout is specified as a symbol, call the requested method and use the layout returned" do controller = WithSymbol.new controller.process(:index) @@ -266,6 +306,13 @@ module AbstractControllerTests assert_equal "With Implied Hello string!", controller.response_body end + test "when a grandchild has nil layout specified, the child has an implied layout, and the " \ + "parent has specified a layout, use the child controller layout" do + controller = WithGrandChildOfImplied.new + controller.process(:index) + assert_equal "With Grand Child Hello string!", controller.response_body + end + test "raises an exception when specifying layout true" do assert_raises ArgumentError do Object.class_eval do @@ -299,6 +346,18 @@ module AbstractControllerTests controller.process(:index) assert_equal "Overwrite Hello index!", controller.response_body end + + test "layout for anonymous controller" do + klass = Class.new(WithString) do + def index + render :text => 'index', :layout => true + end + end + + controller = klass.new + controller.process(:index) + assert_equal "With String index", controller.response_body + end end end end diff --git a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb index 97be5a5bb0..8187eb72d5 100644 --- a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb +++ b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb @@ -130,14 +130,40 @@ class RenderPartialWithRecordIdentificationAndNestedControllersTest < ActiveReco def test_render_with_record_in_nested_controller get :render_with_record_in_nested_controller - assert_template 'fun/games/_game' - assert_equal 'Pong', @response.body + assert_template %r{\Afun/games/_game\Z} + assert_equal "Fun Pong\n", @response.body end def test_render_with_record_collection_in_nested_controller get :render_with_record_collection_in_nested_controller - assert_template 'fun/games/_game' - assert_equal 'PongTank', @response.body + assert_template %r{\Afun/games/_game\Z} + assert_equal "Fun Pong\nFun Tank\n", @response.body + end +end + +class RenderPartialWithRecordIdentificationAndNestedControllersWithoutPrefixTest < ActiveRecordTestCase + tests Fun::NestedController + + def test_render_with_record_in_nested_controller + old_config = ActionView::Base.prefix_partial_path_with_controller_namespace + ActionView::Base.prefix_partial_path_with_controller_namespace = false + + get :render_with_record_in_nested_controller + assert_template %r{\Agames/_game\Z} + assert_equal "Just Pong\n", @response.body + ensure + ActionView::Base.prefix_partial_path_with_controller_namespace = old_config + end + + def test_render_with_record_collection_in_nested_controller + old_config = ActionView::Base.prefix_partial_path_with_controller_namespace + ActionView::Base.prefix_partial_path_with_controller_namespace = false + + get :render_with_record_collection_in_nested_controller + assert_template %r{\Agames/_game\Z} + assert_equal "Just Pong\nJust Tank\n", @response.body + ensure + ActionView::Base.prefix_partial_path_with_controller_namespace = old_config end end @@ -146,13 +172,39 @@ class RenderPartialWithRecordIdentificationAndNestedDeeperControllersTest < Acti def test_render_with_record_in_deeper_nested_controller get :render_with_record_in_deeper_nested_controller - assert_template 'fun/serious/games/_game' - assert_equal 'Chess', @response.body + assert_template %r{\Afun/serious/games/_game\Z} + assert_equal "Serious Chess\n", @response.body end def test_render_with_record_collection_in_deeper_nested_controller get :render_with_record_collection_in_deeper_nested_controller - assert_template 'fun/serious/games/_game' - assert_equal 'ChessSudokuSolitaire', @response.body + assert_template %r{\Afun/serious/games/_game\Z} + assert_equal "Serious Chess\nSerious Sudoku\nSerious Solitaire\n", @response.body + end +end + +class RenderPartialWithRecordIdentificationAndNestedDeeperControllersWithoutPrefixTest < ActiveRecordTestCase + tests Fun::Serious::NestedDeeperController + + def test_render_with_record_in_deeper_nested_controller + old_config = ActionView::Base.prefix_partial_path_with_controller_namespace + ActionView::Base.prefix_partial_path_with_controller_namespace = false + + get :render_with_record_in_deeper_nested_controller + assert_template %r{\Agames/_game\Z} + assert_equal "Just Chess\n", @response.body + ensure + ActionView::Base.prefix_partial_path_with_controller_namespace = old_config + end + + def test_render_with_record_collection_in_deeper_nested_controller + old_config = ActionView::Base.prefix_partial_path_with_controller_namespace + ActionView::Base.prefix_partial_path_with_controller_namespace = false + + get :render_with_record_collection_in_deeper_nested_controller + assert_template %r{\Agames/_game\Z} + assert_equal "Just Chess\nJust Sudoku\nJust Solitaire\n", @response.body + ensure + ActionView::Base.prefix_partial_path_with_controller_namespace = old_config end end diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index d3359e79a6..3d667f0a2f 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -131,6 +131,13 @@ class AssertSelectTest < ActionController::TestCase assert_raise(Assertion) { assert_select "pre", :html=>text } end + def test_strip_textarea + render_html %Q{<textarea>\n\nfoo\n</textarea>} + assert_select "textarea", "\nfoo\n" + render_html %Q{<textarea>\nfoo</textarea>} + assert_select "textarea", "foo" + end + def test_counts render_html %Q{<div id="1">foo</div><div id="2">foo</div>} assert_nothing_raised { assert_select "div", 2 } diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 791edb9069..2d4083252e 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -56,7 +56,7 @@ class UrlOptionsController < ActionController::Base end def url_options - super.merge(:host => 'www.override.com', :action => 'new', :locale => 'en') + super.merge(:host => 'www.override.com') end end @@ -130,8 +130,6 @@ class PerformActionTest < ActionController::TestCase @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.host = "www.nextangle.com" - - rescue_action_in_public! end def test_process_should_be_precise @@ -155,7 +153,6 @@ class UrlOptionsTest < ActionController::TestCase def setup super @request.host = 'www.example.com' - rescue_action_in_public! end def test_url_for_query_params_included @@ -183,9 +180,9 @@ class UrlOptionsTest < ActionController::TestCase get :from_view, :route => "from_view_url" - assert_equal 'http://www.override.com/from_view?locale=en', @response.body - assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url) - assert_equal 'http://www.override.com/default_url_options/new?locale=en', @controller.url_for(:controller => 'default_url_options') + assert_equal 'http://www.override.com/from_view', @response.body + assert_equal 'http://www.override.com/from_view', @controller.send(:from_view_url) + assert_equal 'http://www.override.com/default_url_options/index', @controller.url_for(:controller => 'default_url_options') end end @@ -195,7 +192,6 @@ class UrlOptionsTest < ActionController::TestCase match "account/overview" end - @controller.class.send(:include, set.url_helpers) assert !@controller.class.action_methods.include?("account_overview_path") end end @@ -207,7 +203,6 @@ class DefaultUrlOptionsTest < ActionController::TestCase def setup super @request.host = 'www.example.com' - rescue_action_in_public! end def test_default_url_options_override @@ -258,7 +253,6 @@ class EmptyUrlOptionsTest < ActionController::TestCase def setup super @request.host = 'www.example.com' - rescue_action_in_public! end def test_ensure_url_for_works_as_expected_when_called_with_no_options_if_default_url_options_is_not_set diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb index 7feeda25b3..5b423c8151 100644 --- a/actionpack/test/controller/force_ssl_test.rb +++ b/actionpack/test/controller/force_ssl_test.rb @@ -26,6 +26,14 @@ class ForceSSLExceptAction < ForceSSLController force_ssl :except => :banana end +class ForceSSLIfCondition < ForceSSLController + force_ssl :if => :use_force_ssl? + + def use_force_ssl? + action_name == 'cheeseburger' + end +end + class ForceSSLFlash < ForceSSLController force_ssl :except => [:banana, :set_flash, :use_flash] @@ -109,6 +117,21 @@ class ForceSSLExceptActionTest < ActionController::TestCase end end +class ForceSSLIfConditionTest < ActionController::TestCase + tests ForceSSLIfCondition + + def test_banana_not_redirects_to_https + get :banana + assert_response 200 + end + + def test_cheeseburger_redirects_to_https + get :cheeseburger + assert_response 301 + assert_equal "https://test.host/force_ssl_if_condition/cheeseburger", redirect_to_url + end +end + class ForceSSLFlashTest < ActionController::TestCase tests ForceSSLFlash diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb index a91e3cafa5..828ea5b0fb 100644 --- a/actionpack/test/controller/http_digest_authentication_test.rb +++ b/actionpack/test/controller/http_digest_authentication_test.rb @@ -274,6 +274,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase end def decode_credentials(header) - ActionController::HttpAuthentication::Digest.decode_credentials(@response.headers['WWW-Authenticate']) + ActionController::HttpAuthentication::Digest.decode_credentials(header) end end diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index bc171e201b..c73b36f05e 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -78,6 +78,13 @@ end class DefaultLayoutController < LayoutTest end +class StreamingLayoutController < LayoutTest + def render(*args) + options = args.extract_options! || {} + super(*args, options.merge(:stream => true)) + end +end + class AbsolutePathLayoutController < LayoutTest layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test') end @@ -122,6 +129,12 @@ class LayoutSetInResponseTest < ActionController::TestCase assert_template :layout => "layouts/layout_test" end + def test_layout_set_when_using_streaming_layout + @controller = StreamingLayoutController.new + get :hello + assert_template :hello + end + def test_layout_set_when_set_in_controller @controller = HasOwnLayoutController.new get :hello diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index ae368842b5..0e4099ddc6 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -132,7 +132,6 @@ class RespondToController < ActionController::Base end end - def iphone_with_html_response_type request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone" @@ -1135,7 +1134,7 @@ class PostController < AbstractPostController around_filter :with_iphone def index - respond_to(:html, :iphone) + respond_to(:html, :iphone, :js) end protected @@ -1182,4 +1181,45 @@ class MimeControllerLayoutsTest < ActionController::TestCase get :index assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body end + + def test_non_navigational_format_with_no_template_fallbacks_to_html_template_with_no_layout + get :index, :format => :js + assert_equal "Hello Firefox", @response.body + end +end + +class FlashResponder < ActionController::Responder + def initialize(controller, resources, options={}) + super + end + + def to_html + controller.flash[:notice] = 'Success' + super + end +end + +class FlashResponderController < ActionController::Base + self.responder = FlashResponder + respond_to :html + + def index + respond_with Object.new do |format| + format.html { render :text => 'HTML' } + end + end +end + +class FlashResponderControllerTest < ActionController::TestCase + tests FlashResponderController + + def test_respond_with_block_executed + get :index + assert_equal 'HTML', @response.body + end + + def test_flash_responder_executed + get :index + assert_equal 'Success', flash[:notice] + end end diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index b1d76150f8..6dab42d75d 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -103,6 +103,14 @@ class RedirectController < ActionController::Base redirect_to proc { {:action => "hello_world"} } end + def redirect_with_header_break + redirect_to "/lol\r\nwat" + end + + def redirect_with_null_bytes + redirect_to "\000/lol\r\nwat" + end + def rescue_errors(e) raise e end protected @@ -120,6 +128,18 @@ class RedirectTest < ActionController::TestCase assert_equal "http://test.host/redirect/hello_world", redirect_to_url end + def test_redirect_with_header_break + get :redirect_with_header_break + assert_response :redirect + assert_equal "http://test.host/lolwat", redirect_to_url + end + + def test_redirect_with_null_bytes + get :redirect_with_null_bytes + assert_response :redirect + assert_equal "http://test.host/lolwat", redirect_to_url + end + def test_redirect_with_no_status get :simple_redirect assert_response 302 diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index e040878b26..fce13d096c 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -553,12 +553,33 @@ class TestController < ActionController::Base render :partial => 'partial' end + def partial_html_erb + render :partial => 'partial_html_erb' + end + def render_to_string_with_partial @partial_only = render_to_string :partial => "partial_only" @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") } render :template => "test/hello_world" end + def render_to_string_with_template_and_html_partial + @text = render_to_string :template => "test/with_partial", :formats => [:text] + @html = render_to_string :template => "test/with_partial", :formats => [:html] + render :template => "test/with_html_partial" + end + + def render_to_string_and_render_with_different_formats + @html = render_to_string :template => "test/with_partial", :formats => [:html] + render :template => "test/with_partial", :formats => [:text] + end + + def render_template_within_a_template_with_other_format + render :template => "test/with_xml_template", + :formats => [:html], + :layout => "with_html_partial" + end + def partial_with_counter render :partial => "counter", :locals => { :counter_counter => 5 } end @@ -1001,6 +1022,7 @@ class RenderTest < ActionController::TestCase def test_accessing_local_assigns_in_inline_template get :accessing_local_assigns_in_inline_template, :local_name => "Local David" assert_equal "Goodbye, Local David", @response.body + assert_equal "text/html", @response.content_type end def test_should_implicitly_render_html_template_from_xhr_request @@ -1246,22 +1268,57 @@ class RenderTest < ActionController::TestCase def test_partial_only get :partial_only assert_equal "only partial", @response.body + assert_equal "text/html", @response.content_type end def test_should_render_html_formatted_partial get :partial - assert_equal 'partial html', @response.body + assert_equal "partial html", @response.body + assert_equal "text/html", @response.content_type + end + + def test_render_html_formatted_partial_even_with_other_mime_time_in_accept + @request.accept = "text/javascript, text/html" + + get :partial_html_erb + + assert_equal "partial.html.erb", @response.body.strip + assert_equal "text/html", @response.content_type end def test_should_render_html_partial_with_formats get :partial_formats_html - assert_equal 'partial html', @response.body + assert_equal "partial html", @response.body + assert_equal "text/html", @response.content_type end def test_render_to_string_partial get :render_to_string_with_partial assert_equal "only partial", assigns(:partial_only) assert_equal "Hello: david", assigns(:partial_with_locals) + assert_equal "text/html", @response.content_type + end + + def test_render_to_string_with_template_and_html_partial + get :render_to_string_with_template_and_html_partial + assert_equal "**only partial**\n", assigns(:text) + assert_equal "<strong>only partial</strong>\n", assigns(:html) + assert_equal "<strong>only html partial</strong>\n", @response.body + assert_equal "text/html", @response.content_type + end + + def test_render_to_string_and_render_with_different_formats + get :render_to_string_and_render_with_different_formats + assert_equal "<strong>only partial</strong>\n", assigns(:html) + assert_equal "**only partial**\n", @response.body + assert_equal "text/plain", @response.content_type + end + + def test_render_template_within_a_template_with_other_format + get :render_template_within_a_template_with_other_format + expected = "only html partial<p>This is grand!</p>" + assert_equal expected, @response.body.strip + assert_equal "text/html", @response.content_type end def test_partial_with_counter diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 64ed7f667f..066cd523be 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -35,6 +35,24 @@ module RequestForgeryProtectionActions def form_for_without_protection render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>" end + + def form_for_remote + render :inline => "<%= form_for(:some_resource, :remote => true ) {} %>" + end + + def form_for_remote_with_token + render :inline => "<%= form_for(:some_resource, :remote => true, :authenticity_token => true ) {} %>" + end + + def form_for_with_token + render :inline => "<%= form_for(:some_resource, :authenticity_token => true ) {} %>" + end + + def form_for_remote_with_external_token + render :inline => "<%= form_for(:some_resource, :remote => true, :authenticity_token => 'external_token') {} %>" + end + + def rescue_action(e) raise e end end # sample controllers @@ -43,7 +61,7 @@ class RequestForgeryProtectionController < ActionController::Base protect_from_forgery :only => %w(index meta) end -class RequestForgeryProtectionControllerUsingOldBehaviour < ActionController::Base +class RequestForgeryProtectionControllerUsingException < ActionController::Base include RequestForgeryProtectionActions protect_from_forgery :only => %w(index meta) @@ -98,6 +116,60 @@ module RequestForgeryProtectionTests assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token end + def test_should_render_form_without_token_tag_if_remote + assert_not_blocked do + get :form_for_remote + end + assert_no_match(/authenticity_token/, response.body) + end + + def test_should_render_form_with_token_tag_if_remote_and_embedding_token_is_on + original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms + begin + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true + assert_not_blocked do + get :form_for_remote + end + assert_match(/authenticity_token/, response.body) + ensure + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original + end + end + + def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested_and_embedding_is_on + original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms + begin + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true + assert_not_blocked do + get :form_for_remote_with_external_token + end + assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', 'external_token' + ensure + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original + end + end + + def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested + assert_not_blocked do + get :form_for_remote_with_external_token + end + assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', 'external_token' + end + + def test_should_render_form_with_token_tag_if_remote_and_authenticity_token_requested + assert_not_blocked do + get :form_for_remote_with_token + end + assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token + end + + def test_should_render_form_with_token_tag_with_authenticity_token_requested + assert_not_blocked do + get :form_for_with_token + end + assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token + end + def test_should_allow_get assert_not_blocked { get :index } end @@ -215,7 +287,7 @@ class RequestForgeryProtectionControllerTest < ActionController::TestCase end end -class RequestForgeryProtectionControllerUsingOldBehaviourTest < ActionController::TestCase +class RequestForgeryProtectionControllerUsingExceptionTest < ActionController::TestCase include RequestForgeryProtectionTests def assert_blocked assert_raises(ActionController::InvalidAuthenticityToken) do diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 843ae1a813..272a7da8c5 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -59,11 +59,11 @@ end class MockController def self.build(helpers) Class.new do - def url_for(options) + def url_options + options = super options[:protocol] ||= "http" options[:host] ||= "test.host" - - super(options) + options end include helpers @@ -437,6 +437,15 @@ class LegacyRouteSetTests < ActiveSupport::TestCase assert_equal("/", routes.send(:root_path)) end + def test_named_route_root_without_hash + rs.draw do + root "hello#index" + end + routes = setup_for_named_route + assert_equal("http://test.host/", routes.send(:root_url)) + assert_equal("/", routes.send(:root_path)) + end + def test_named_route_with_regexps rs.draw do match 'page/:year/:month/:day/:title' => 'page#show', :as => 'article', diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index 36884846be..3af17f495c 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -23,10 +23,6 @@ class SendFileController < ActionController::Base def data send_data(file_data, options) end - - def multibyte_text_data - send_data("Кирилица\n祝您好運.", options) - end end class SendFileTest < ActionController::TestCase diff --git a/actionpack/test/controller/sweeper_test.rb b/actionpack/test/controller/sweeper_test.rb new file mode 100644 index 0000000000..0561efc62f --- /dev/null +++ b/actionpack/test/controller/sweeper_test.rb @@ -0,0 +1,16 @@ +require 'abstract_unit' + + +class SweeperTest < ActionController::TestCase + + class ::AppSweeper < ActionController::Caching::Sweeper; end + + def test_sweeper_should_not_ignore_unknown_method_calls + sweeper = ActionController::Caching::Sweeper.send(:new) + assert_raise NameError do + sweeper.instance_eval do + some_method_that_doesnt_exist + end + end + end +end diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 288efbf7c3..aa233d6135 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -16,6 +16,10 @@ module AbstractController W.default_url_options[:host] = 'www.basecamphq.com' end + def add_port! + W.default_url_options[:port] = 3000 + end + def add_numeric_host! W.default_url_options[:host] = '127.0.0.1' end @@ -121,6 +125,14 @@ module AbstractController ) end + def test_default_port + add_host! + add_port! + assert_equal('http://www.basecamphq.com:3000/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i') + ) + end + def test_protocol add_host! assert_equal('https://www.basecamphq.com/c/a/i', diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb index 0372c42920..e3f9faaa64 100644 --- a/actionpack/test/dispatch/mime_type_test.rb +++ b/actionpack/test/dispatch/mime_type_test.rb @@ -75,6 +75,12 @@ class MimeTypeTest < ActiveSupport::TestCase assert_equal expect, Mime::Type.parse(accept) end + test "parse arbitarry media type parameters" do + accept = 'multipart/form-data; boundary="simple boundary"' + expect = [Mime::MULTIPART_FORM] + assert_equal expect, Mime::Type.parse(accept) + end + # Accept header send with user HTTP_USER_AGENT: Sunrise/0.42j (Windows XP) test "parse broken acceptlines" do accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5" diff --git a/actionpack/test/dispatch/routing_assertions_test.rb b/actionpack/test/dispatch/routing_assertions_test.rb index 9f95d82129..e953029456 100644 --- a/actionpack/test/dispatch/routing_assertions_test.rb +++ b/actionpack/test/dispatch/routing_assertions_test.rb @@ -3,6 +3,7 @@ require 'controller/fake_controllers' class SecureArticlesController < ArticlesController; end class BlockArticlesController < ArticlesController; end +class QueryArticlesController < ArticlesController; end class RoutingAssertionsTest < ActionController::TestCase @@ -18,6 +19,10 @@ class RoutingAssertionsTest < ActionController::TestCase scope 'block', :constraints => lambda { |r| r.ssl? } do resources :articles, :controller => 'block_articles' end + + scope 'query', :constraints => lambda { |r| r.params[:use_query] == 'true' } do + resources :articles, :controller => 'query_articles' + end end end @@ -62,6 +67,13 @@ class RoutingAssertionsTest < ActionController::TestCase assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'https://test.host/block/articles') end + def test_assert_recognizes_with_query_constraint + assert_raise(ActionController::RoutingError) do + assert_recognizes({ :controller => 'query_articles', :action => 'index', :use_query => 'false' }, '/query/articles', { :use_query => 'false' }) + end + assert_recognizes({ :controller => 'query_articles', :action => 'index', :use_query => 'true' }, '/query/articles', { :use_query => 'true' }) + end + def test_assert_routing assert_routing('/articles', :controller => 'articles', :action => 'index') end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 700666600b..cc4279d9dd 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -475,6 +475,11 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest get :preview, :on => :member end + resources :profiles, :param => :username do + get :details, :on => :member + resources :messages + end + scope :as => "routes" do get "/c/:id", :as => :collision, :to => "collision#show" get "/collision", :to => "collision#show" @@ -2183,6 +2188,19 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest assert_equal "/posts/1/admin", post_admin_root_path(:post_id => '1') end + def test_custom_param + get '/profiles/bob' + assert_equal 'profiles#show', @response.body + assert_equal 'bob', @request.params[:username] + + get '/profiles/bob/details' + assert_equal 'bob', @request.params[:username] + + get '/profiles/bob/messages/34' + assert_equal 'bob', @request.params[:profile_username] + assert_equal '34', @request.params[:id] + end + private def with_https old_https = https? diff --git a/actionpack/test/dispatch/ssl_test.rb b/actionpack/test/dispatch/ssl_test.rb new file mode 100644 index 0000000000..6f075a9074 --- /dev/null +++ b/actionpack/test/dispatch/ssl_test.rb @@ -0,0 +1,157 @@ +require 'abstract_unit' + +class SSLTest < ActionDispatch::IntegrationTest + def default_app + lambda { |env| + headers = {'Content-Type' => "text/html"} + headers['Set-Cookie'] = "id=1; path=/\ntoken=abc; path=/; secure; HttpOnly" + [200, headers, ["OK"]] + } + end + + def app + @app ||= ActionDispatch::SSL.new(default_app) + end + attr_writer :app + + def test_allows_https_url + get "https://example.org/path?key=value" + assert_response :success + end + + def test_allows_https_proxy_header_url + get "http://example.org/", {}, 'HTTP_X_FORWARDED_PROTO' => "https" + assert_response :success + end + + def test_redirects_http_to_https + get "http://example.org/path?key=value" + assert_response :redirect + assert_equal "https://example.org/path?key=value", + response.headers['Location'] + end + + def test_hsts_header_by_default + get "https://example.org/" + assert_equal "max-age=31536000", + response.headers['Strict-Transport-Security'] + end + + def test_hsts_header + self.app = ActionDispatch::SSL.new(default_app, :hsts => true) + get "https://example.org/" + assert_equal "max-age=31536000", + response.headers['Strict-Transport-Security'] + end + + def test_disable_hsts_header + self.app = ActionDispatch::SSL.new(default_app, :hsts => false) + get "https://example.org/" + refute response.headers['Strict-Transport-Security'] + end + + def test_hsts_expires + self.app = ActionDispatch::SSL.new(default_app, :hsts => { :expires => 500 }) + get "https://example.org/" + assert_equal "max-age=500", + response.headers['Strict-Transport-Security'] + end + + def test_hsts_include_subdomains + self.app = ActionDispatch::SSL.new(default_app, :hsts => { :subdomains => true }) + get "https://example.org/" + assert_equal "max-age=31536000; includeSubDomains", + response.headers['Strict-Transport-Security'] + end + + def test_flag_cookies_as_secure + get "https://example.org/" + assert_equal ["id=1; path=/; secure", "token=abc; path=/; secure; HttpOnly" ], + response.headers['Set-Cookie'].split("\n") + end + + def test_flag_cookies_as_secure_at_end_of_line + self.app = ActionDispatch::SSL.new(lambda { |env| + headers = { + 'Content-Type' => "text/html", + 'Set-Cookie' => "problem=def; path=/; HttpOnly; secure" + } + [200, headers, ["OK"]] + }) + + get "https://example.org/" + assert_equal ["problem=def; path=/; HttpOnly; secure"], + response.headers['Set-Cookie'].split("\n") + end + + def test_flag_cookies_as_secure_with_more_spaces_before + self.app = ActionDispatch::SSL.new(lambda { |env| + headers = { + 'Content-Type' => "text/html", + 'Set-Cookie' => "problem=def; path=/; HttpOnly; secure" + } + [200, headers, ["OK"]] + }) + + get "https://example.org/" + assert_equal ["problem=def; path=/; HttpOnly; secure"], + response.headers['Set-Cookie'].split("\n") + end + + def test_flag_cookies_as_secure_with_more_spaces_after + self.app = ActionDispatch::SSL.new(lambda { |env| + headers = { + 'Content-Type' => "text/html", + 'Set-Cookie' => "problem=def; path=/; secure; HttpOnly" + } + [200, headers, ["OK"]] + }) + + get "https://example.org/" + assert_equal ["problem=def; path=/; secure; HttpOnly"], + response.headers['Set-Cookie'].split("\n") + end + + def test_no_cookies + self.app = ActionDispatch::SSL.new(lambda { |env| + [200, {'Content-Type' => "text/html"}, ["OK"]] + }) + get "https://example.org/" + assert !response.headers['Set-Cookie'] + end + + def test_redirect_to_host + self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org") + get "http://example.org/path?key=value" + assert_equal "https://ssl.example.org/path?key=value", + response.headers['Location'] + end + + def test_redirect_to_port + self.app = ActionDispatch::SSL.new(default_app, :port => 8443) + get "http://example.org/path?key=value" + assert_equal "https://example.org:8443/path?key=value", + response.headers['Location'] + end + + def test_redirect_to_host_and_port + self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org", :port => 8443) + get "http://example.org/path?key=value" + assert_equal "https://ssl.example.org:8443/path?key=value", + response.headers['Location'] + end + + def test_redirect_to_secure_host_when_on_subdomain + self.app = ActionDispatch::SSL.new(default_app, :host => "ssl.example.org") + get "http://ssl.example.org/path?key=value" + assert_equal "https://ssl.example.org/path?key=value", + response.headers['Location'] + end + + def test_redirect_to_secure_subdomain_when_on_deep_subdomain + self.app = ActionDispatch::SSL.new(default_app, :host => "example.co.uk") + get "http://double.rainbow.what.does.it.mean.example.co.uk/path?key=value" + assert_equal "https://example.co.uk/path?key=value", + response.headers['Location'] + end +end diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb index 092ca3e20a..112f470786 100644 --- a/actionpack/test/dispatch/static_test.rb +++ b/actionpack/test/dispatch/static_test.rb @@ -7,6 +7,10 @@ module StaticTests assert_equal "Hello, World!", get("/nofile").body end + def test_handles_urls_with_bad_encoding + assert_equal "Hello, World!", get("/doorkeeper%E3E4").body + end + def test_sets_cache_control response = get("/index.html") assert_html "/index.html", response diff --git a/actionpack/test/dispatch/uploaded_file_test.rb b/actionpack/test/dispatch/uploaded_file_test.rb index 0b95291e18..e69c1fbed4 100644 --- a/actionpack/test/dispatch/uploaded_file_test.rb +++ b/actionpack/test/dispatch/uploaded_file_test.rb @@ -12,7 +12,7 @@ module ActionDispatch uf = Http::UploadedFile.new(:filename => 'foo', :tempfile => Object.new) assert_equal 'foo', uf.original_filename end - + def test_filename_should_be_in_utf_8 uf = Http::UploadedFile.new(:filename => 'foo', :tempfile => Object.new) assert_equal "UTF-8", uf.original_filename.encoding.to_s @@ -65,6 +65,12 @@ module ActionDispatch end end + def test_delegate_eof_to_tempfile + tf = Class.new { def eof?; true end; } + uf = Http::UploadedFile.new(:tempfile => tf.new) + assert uf.eof? + end + def test_respond_to? tf = Class.new { def read; yield end } uf = Http::UploadedFile.new(:tempfile => tf.new) diff --git a/actionpack/test/fixtures/fun/games/_game.erb b/actionpack/test/fixtures/fun/games/_game.erb index d51b7b3ebc..f0f542ff92 100644 --- a/actionpack/test/fixtures/fun/games/_game.erb +++ b/actionpack/test/fixtures/fun/games/_game.erb @@ -1 +1 @@ -<%= game.name %>
\ No newline at end of file +Fun <%= game.name %> diff --git a/actionpack/test/fixtures/fun/serious/games/_game.erb b/actionpack/test/fixtures/fun/serious/games/_game.erb index d51b7b3ebc..523bc55bd7 100644 --- a/actionpack/test/fixtures/fun/serious/games/_game.erb +++ b/actionpack/test/fixtures/fun/serious/games/_game.erb @@ -1 +1 @@ -<%= game.name %>
\ No newline at end of file +Serious <%= game.name %> diff --git a/actionpack/test/fixtures/games/_game.erb b/actionpack/test/fixtures/games/_game.erb new file mode 100644 index 0000000000..1aeb81fcba --- /dev/null +++ b/actionpack/test/fixtures/games/_game.erb @@ -0,0 +1 @@ +Just <%= game.name %> diff --git a/actionpack/test/fixtures/layouts/with_html_partial.html.erb b/actionpack/test/fixtures/layouts/with_html_partial.html.erb new file mode 100644 index 0000000000..fd2896aeaa --- /dev/null +++ b/actionpack/test/fixtures/layouts/with_html_partial.html.erb @@ -0,0 +1 @@ +<%= render :partial => "partial_only_html" %><%= yield %> diff --git a/actionpack/test/fixtures/reply.rb b/actionpack/test/fixtures/reply.rb index 19cba93673..0d3b0a7c98 100644 --- a/actionpack/test/fixtures/reply.rb +++ b/actionpack/test/fixtures/reply.rb @@ -1,5 +1,5 @@ class Reply < ActiveRecord::Base - scope :base + scope :base, -> { scoped } belongs_to :topic, :include => [:replies] belongs_to :developer diff --git a/actionpack/test/fixtures/sprockets/alternate/stylesheets/style.css b/actionpack/test/fixtures/sprockets/alternate/stylesheets/style.css deleted file mode 100644 index bfb90bfa48..0000000000 --- a/actionpack/test/fixtures/sprockets/alternate/stylesheets/style.css +++ /dev/null @@ -1 +0,0 @@ -/* Different from other style.css */
\ No newline at end of file diff --git a/actionpack/test/fixtures/sprockets/app/fonts/dir/font.ttf b/actionpack/test/fixtures/sprockets/app/fonts/dir/font.ttf deleted file mode 100644 index e69de29bb2..0000000000 --- a/actionpack/test/fixtures/sprockets/app/fonts/dir/font.ttf +++ /dev/null diff --git a/actionpack/test/fixtures/sprockets/app/fonts/font.ttf b/actionpack/test/fixtures/sprockets/app/fonts/font.ttf deleted file mode 100644 index e69de29bb2..0000000000 --- a/actionpack/test/fixtures/sprockets/app/fonts/font.ttf +++ /dev/null diff --git a/actionpack/test/fixtures/sprockets/app/images/logo.png b/actionpack/test/fixtures/sprockets/app/images/logo.png Binary files differdeleted file mode 100644 index d5edc04e65..0000000000 --- a/actionpack/test/fixtures/sprockets/app/images/logo.png +++ /dev/null diff --git a/actionpack/test/fixtures/sprockets/app/javascripts/application.js b/actionpack/test/fixtures/sprockets/app/javascripts/application.js deleted file mode 100644 index e611d2b129..0000000000 --- a/actionpack/test/fixtures/sprockets/app/javascripts/application.js +++ /dev/null @@ -1 +0,0 @@ -//= require xmlhr diff --git a/actionpack/test/fixtures/sprockets/app/javascripts/dir/xmlhr.js b/actionpack/test/fixtures/sprockets/app/javascripts/dir/xmlhr.js deleted file mode 100644 index e69de29bb2..0000000000 --- a/actionpack/test/fixtures/sprockets/app/javascripts/dir/xmlhr.js +++ /dev/null diff --git a/actionpack/test/fixtures/sprockets/app/javascripts/extra.js b/actionpack/test/fixtures/sprockets/app/javascripts/extra.js deleted file mode 100644 index e69de29bb2..0000000000 --- a/actionpack/test/fixtures/sprockets/app/javascripts/extra.js +++ /dev/null diff --git a/actionpack/test/fixtures/sprockets/app/javascripts/xmlhr.js b/actionpack/test/fixtures/sprockets/app/javascripts/xmlhr.js deleted file mode 100644 index e69de29bb2..0000000000 --- a/actionpack/test/fixtures/sprockets/app/javascripts/xmlhr.js +++ /dev/null diff --git a/actionpack/test/fixtures/sprockets/app/stylesheets/application.css b/actionpack/test/fixtures/sprockets/app/stylesheets/application.css deleted file mode 100644 index 2365eaa4cd..0000000000 --- a/actionpack/test/fixtures/sprockets/app/stylesheets/application.css +++ /dev/null @@ -1 +0,0 @@ -/*= require style */ diff --git a/actionpack/test/fixtures/sprockets/app/stylesheets/dir/style.css b/actionpack/test/fixtures/sprockets/app/stylesheets/dir/style.css deleted file mode 100644 index e69de29bb2..0000000000 --- a/actionpack/test/fixtures/sprockets/app/stylesheets/dir/style.css +++ /dev/null diff --git a/actionpack/test/fixtures/sprockets/app/stylesheets/extra.css b/actionpack/test/fixtures/sprockets/app/stylesheets/extra.css deleted file mode 100644 index e69de29bb2..0000000000 --- a/actionpack/test/fixtures/sprockets/app/stylesheets/extra.css +++ /dev/null diff --git a/actionpack/test/fixtures/sprockets/app/stylesheets/style.css b/actionpack/test/fixtures/sprockets/app/stylesheets/style.css deleted file mode 100644 index e69de29bb2..0000000000 --- a/actionpack/test/fixtures/sprockets/app/stylesheets/style.css +++ /dev/null diff --git a/actionpack/test/fixtures/test/_b_layout_for_partial.html.erb b/actionpack/test/fixtures/test/_b_layout_for_partial.html.erb new file mode 100644 index 0000000000..e918ba8f83 --- /dev/null +++ b/actionpack/test/fixtures/test/_b_layout_for_partial.html.erb @@ -0,0 +1 @@ +<b><%= yield %></b>
\ No newline at end of file diff --git a/actionpack/test/fixtures/test/_partial_html_erb.html.erb b/actionpack/test/fixtures/test/_partial_html_erb.html.erb new file mode 100644 index 0000000000..4b54875782 --- /dev/null +++ b/actionpack/test/fixtures/test/_partial_html_erb.html.erb @@ -0,0 +1 @@ +<%= "partial.html.erb" %> diff --git a/actionpack/test/fixtures/test/_partial_only_html.html b/actionpack/test/fixtures/test/_partial_only_html.html new file mode 100644 index 0000000000..d2d630bd40 --- /dev/null +++ b/actionpack/test/fixtures/test/_partial_only_html.html @@ -0,0 +1 @@ +only html partial
\ No newline at end of file diff --git a/actionpack/test/fixtures/test/with_html_partial.html.erb b/actionpack/test/fixtures/test/with_html_partial.html.erb new file mode 100644 index 0000000000..d84d909d64 --- /dev/null +++ b/actionpack/test/fixtures/test/with_html_partial.html.erb @@ -0,0 +1 @@ +<strong><%= render :partial => "partial_only_html" %></strong> diff --git a/actionpack/test/fixtures/test/with_partial.html.erb b/actionpack/test/fixtures/test/with_partial.html.erb new file mode 100644 index 0000000000..7502364cf5 --- /dev/null +++ b/actionpack/test/fixtures/test/with_partial.html.erb @@ -0,0 +1 @@ +<strong><%= render :partial => "partial_only" %></strong> diff --git a/actionpack/test/fixtures/test/with_partial.text.erb b/actionpack/test/fixtures/test/with_partial.text.erb new file mode 100644 index 0000000000..5f068ebf27 --- /dev/null +++ b/actionpack/test/fixtures/test/with_partial.text.erb @@ -0,0 +1 @@ +**<%= render :partial => "partial_only" %>** diff --git a/actionpack/test/fixtures/test/with_xml_template.html.erb b/actionpack/test/fixtures/test/with_xml_template.html.erb new file mode 100644 index 0000000000..e54a7cd001 --- /dev/null +++ b/actionpack/test/fixtures/test/with_xml_template.html.erb @@ -0,0 +1 @@ +<%= render :template => "test/greeting", :formats => :xml %> diff --git a/actionpack/test/template/active_model_helper_test.rb b/actionpack/test/template/active_model_helper_test.rb index 52be0f1762..24511df444 100644 --- a/actionpack/test/template/active_model_helper_test.rb +++ b/actionpack/test/template/active_model_helper_test.rb @@ -29,28 +29,28 @@ class ActiveModelHelperTest < ActionView::TestCase def test_text_area_with_errors assert_dom_equal( - %(<div class="field_with_errors"><textarea cols="40" id="post_body" name="post[body]" rows="20">Back to the hill and over it again!</textarea></div>), + %(<div class="field_with_errors"><textarea id="post_body" name="post[body]">\nBack to the hill and over it again!</textarea></div>), text_area("post", "body") ) end def test_text_field_with_errors assert_dom_equal( - %(<div class="field_with_errors"><input id="post_author_name" name="post[author_name]" size="30" type="text" value="" /></div>), + %(<div class="field_with_errors"><input id="post_author_name" name="post[author_name]" type="text" value="" /></div>), text_field("post", "author_name") ) end def test_date_select_with_errors assert_dom_equal( - %(<div class="field_with_errors"><select id="post_updated_at_1i" name="post[updated_at(1i)]">\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n</select>\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n</div>), + %(<div class="field_with_errors"><select id="post_updated_at_1i" name="post[updated_at(1i)]">\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n</select>\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="1" />\n</div>), date_select("post", "updated_at", :discard_month => true, :discard_day => true, :start_year => 2004, :end_year => 2005) ) end def test_datetime_select_with_errors assert_dom_equal( - %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n : <select id="post_updated_at_5i" name="post[updated_at(5i)]">\n<option selected="selected" value="00">00</option>\n</select>\n</div>), + %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="1" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n : <select id="post_updated_at_5i" name="post[updated_at(5i)]">\n<option selected="selected" value="00">00</option>\n</select>\n</div>), datetime_select("post", "updated_at", :discard_year => true, :discard_month => true, :discard_day => true, :minute_step => 60) ) end @@ -76,7 +76,7 @@ class ActiveModelHelperTest < ActionView::TestCase end assert_dom_equal( - %(<div class="field_with_errors"><input id="post_author_name" name="post[author_name]" size="30" type="text" value="" /> <span class="error">can't be empty</span></div>), + %(<div class="field_with_errors"><input id="post_author_name" name="post[author_name]" type="text" value="" /> <span class="error">can't be empty</span></div>), text_field("post", "author_name") ) ensure diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index 3d2eeea503..58ff055fc2 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -38,6 +38,7 @@ class AssetTagHelperTest < ActionView::TestCase @controller = BasicController.new @request = Class.new do + attr_accessor :script_name def protocol() 'http://' end def ssl?() false end def host_with_port() 'localhost' end @@ -647,6 +648,13 @@ class AssetTagHelperTest < ActionView::TestCase assert_equal %(<img alt="Rails" src="#{@controller.config.relative_url_root}/images/rails.png?#{expected_time}" />), image_tag("rails.png") end + # Same as above, but with script_name + def test_timebased_asset_id_with_script_name + @request.script_name = "/collaboration/hieraki" + expected_time = File.mtime(File.expand_path(File.dirname(__FILE__) + "/../fixtures/public/images/rails.png")).to_i.to_s + assert_equal %(<img alt="Rails" src="#{@request.script_name}/images/rails.png?#{expected_time}" />), image_tag("rails.png") + end + def test_should_skip_asset_id_on_complete_url assert_equal %(<img alt="Rails" src="http://www.example.com/rails.png" />), image_tag("http://www.example.com/rails.png") end @@ -897,6 +905,31 @@ class AssetTagHelperTest < ActionView::TestCase FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js')) end + # Same as above, but with script_name + def test_caching_javascript_include_tag_with_script_name + ENV["RAILS_ASSET_ID"] = "" + @request.script_name = "/collaboration/hieraki" + config.perform_caching = true + + assert_dom_equal( + %(<script src="/collaboration/hieraki/javascripts/all.js" type="text/javascript"></script>), + javascript_include_tag(:all, :cache => true) + ) + + assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js')) + + assert_dom_equal( + %(<script src="/collaboration/hieraki/javascripts/money.js" type="text/javascript"></script>), + javascript_include_tag(:all, :cache => "money") + ) + + assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js')) + + ensure + FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js')) + FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js')) + end + def test_caching_javascript_include_tag_with_named_paths_and_relative_url_root_when_caching_off ENV["RAILS_ASSET_ID"] = "" @controller.config.relative_url_root = "/collaboration/hieraki" @@ -917,6 +950,27 @@ class AssetTagHelperTest < ActionView::TestCase assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js')) end + # Same as above, but with script_name + def test_caching_javascript_include_tag_with_named_paths_and_script_name_when_caching_off + ENV["RAILS_ASSET_ID"] = "" + @request.script_name = "/collaboration/hieraki" + config.perform_caching = false + + assert_dom_equal( + %(<script src="/collaboration/hieraki/javascripts/robber.js" type="text/javascript"></script>), + javascript_include_tag('robber', :cache => true) + ) + + assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js')) + + assert_dom_equal( + %(<script src="/collaboration/hieraki/javascripts/robber.js" type="text/javascript"></script>), + javascript_include_tag('robber', :cache => "money", :recursive => true) + ) + + assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js')) + end + def test_caching_javascript_include_tag_when_caching_off ENV["RAILS_ASSET_ID"] = "" config.perform_caching = false @@ -1144,6 +1198,33 @@ class AssetTagHelperTest < ActionView::TestCase FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css')) end + # Same as above, but with script_name + def test_caching_stylesheet_link_tag_with_script_name + ENV["RAILS_ASSET_ID"] = "" + @request.script_name = "/collaboration/hieraki" + config.perform_caching = true + + assert_dom_equal( + %(<link href="/collaboration/hieraki/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />), + stylesheet_link_tag(:all, :cache => true) + ) + + files_to_be_joined = Dir["#{ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR}/[^all]*.css"] + + expected_mtime = files_to_be_joined.map { |p| File.mtime(p) }.max + assert_equal expected_mtime, File.mtime(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'all.css')) + + assert_dom_equal( + %(<link href="/collaboration/hieraki/stylesheets/money.css" media="screen" rel="stylesheet" type="text/css" />), + stylesheet_link_tag(:all, :cache => "money") + ) + + assert File.exist?(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css')) + ensure + FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'all.css')) + FileUtils.rm_f(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css')) + end + def test_caching_stylesheet_link_tag_with_named_paths_and_relative_url_root_when_caching_off ENV["RAILS_ASSET_ID"] = "" @@ -1165,6 +1246,27 @@ class AssetTagHelperTest < ActionView::TestCase assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css')) end + # Same as above, but with script_name + def test_caching_stylesheet_link_tag_with_named_paths_and_script_name_when_caching_off + ENV["RAILS_ASSET_ID"] = "" + @request.script_name = "/collaboration/hieraki" + config.perform_caching = false + + assert_dom_equal( + %(<link href="/collaboration/hieraki/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />), + stylesheet_link_tag('robber', :cache => true) + ) + + assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'all.css')) + + assert_dom_equal( + %(<link href="/collaboration/hieraki/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />), + stylesheet_link_tag('robber', :cache => "money") + ) + + assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::STYLESHEETS_DIR, 'money.css')) + end + diff --git a/actionpack/test/template/atom_feed_helper_test.rb b/actionpack/test/template/atom_feed_helper_test.rb index d26aa9aa85..89aae4ac56 100644 --- a/actionpack/test/template/atom_feed_helper_test.rb +++ b/actionpack/test/template/atom_feed_helper_test.rb @@ -45,6 +45,23 @@ class ScrollsController < ActionController::Base end end EOT + FEEDS["entry_type_options"] = <<-EOT + atom_feed(:schema_date => '2008') do |feed| + feed.title("My great blog!") + feed.updated((@scrolls.first.created_at)) + + @scrolls.each do |scroll| + feed.entry(scroll, :type => 'text/xml') do |entry| + entry.title(scroll.title) + entry.content(scroll.body, :type => 'html') + + entry.author do |author| + author.name("DHH") + end + end + end + end + EOT FEEDS["xml_block"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") @@ -306,6 +323,20 @@ class AtomFeedTest < ActionController::TestCase end end + def test_feed_entry_type_option_default_to_text_html + with_restful_routing(:scrolls) do + get :index, :id => 'defaults' + assert_select "entry link[rel=alternate][type=text/html]" + end + end + + def test_feed_entry_type_option_specified + with_restful_routing(:scrolls) do + get :index, :id => 'entry_type_options' + assert_select "entry link[rel=alternate][type=text/xml]" + end + end + private def with_restful_routing(resources) with_routing do |set| diff --git a/actionpack/test/template/compressors_test.rb b/actionpack/test/template/compressors_test.rb deleted file mode 100644 index a273f15bd7..0000000000 --- a/actionpack/test/template/compressors_test.rb +++ /dev/null @@ -1,28 +0,0 @@ -require 'abstract_unit' -require 'sprockets/compressors' - -class CompressorsTest < ActiveSupport::TestCase - def test_register_css_compressor - Sprockets::Compressors.register_css_compressor(:null, Sprockets::NullCompressor) - compressor = Sprockets::Compressors.registered_css_compressor(:null) - assert_kind_of Sprockets::NullCompressor, compressor - end - - def test_register_js_compressor - Sprockets::Compressors.register_js_compressor(:uglifier, 'Uglifier', :require => 'uglifier') - compressor = Sprockets::Compressors.registered_js_compressor(:uglifier) - assert_kind_of Uglifier, compressor - end - - def test_register_default_css_compressor - Sprockets::Compressors.register_css_compressor(:null, Sprockets::NullCompressor, :default => true) - compressor = Sprockets::Compressors.registered_css_compressor(:default) - assert_kind_of Sprockets::NullCompressor, compressor - end - - def test_register_default_js_compressor - Sprockets::Compressors.register_js_compressor(:null, Sprockets::NullCompressor, :default => true) - compressor = Sprockets::Compressors.registered_js_compressor(:default) - assert_kind_of Sprockets::NullCompressor, compressor - end -end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index 9e2f4ec347..c9b8a5bb70 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -711,7 +711,7 @@ class DateHelperTest < ActionView::TestCase # Since the order is incomplete nothing will be shown expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n) expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n) - expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="16" />\n) + expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="1" />\n) assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :order => [:day]) end @@ -943,7 +943,7 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" expected << %(<input type="hidden" id="date_first_month" name="date[first][month]" value="8" />\n) - expected << %(<input type="hidden" id="date_first_day" name="date[first][day]" value="16" />\n) + expected << %(<input type="hidden" id="date_first_day" name="date[first][day]" value="1" />\n) assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :discard_month => true, :discard_day => true, :start_year => 2003, :end_year => 2005, :prefix => "date[first]"}) end @@ -1396,6 +1396,20 @@ class DateHelperTest < ActionView::TestCase assert_dom_equal expected, date_select("post", "written_on", :order => [ :month, :year ]) end + def test_date_select_without_day_and_month + @post = Post.new + @post.written_on = Date.new(2004, 2, 29) + + expected = "<input type=\"hidden\" id=\"post_written_on_2i\" name=\"post[written_on(2i)]\" value=\"2\" />\n" + expected << "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n" + + expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} + expected << "</select>\n" + + assert_dom_equal expected, date_select("post", "written_on", :order => [ :year ]) + end + def test_date_select_without_day_with_separator @post = Post.new @post.written_on = Date.new(2004, 6, 15) @@ -2118,6 +2132,18 @@ class DateHelperTest < ActionView::TestCase assert_dom_equal expected, datetime_select("post", "updated_at", { :date_separator => " / ", :datetime_separator => " , ", :time_separator => " - ", :include_seconds => true }) end + def test_datetime_select_with_integer + @post = Post.new + @post.updated_at = 3 + datetime_select("post", "updated_at") + end + + def test_datetime_select_with_infinity # Float + @post = Post.new + @post.updated_at = (-1.0/0) + datetime_select("post", "updated_at") + end + def test_datetime_select_with_default_prompt @post = Post.new @post.updated_at = nil @@ -2427,7 +2453,7 @@ class DateHelperTest < ActionView::TestCase 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) } expected << "</select>\n" expected << %{<input type="hidden" id="post_updated_at_2i" name="post[updated_at(2i)]" value="6" />\n} - expected << %{<input type="hidden" id="post_updated_at_3i" name="post[updated_at(3i)]" value="15" />\n} + expected << %{<input type="hidden" id="post_updated_at_3i" name="post[updated_at(3i)]" value="1" />\n} expected << " — " @@ -2448,7 +2474,7 @@ class DateHelperTest < ActionView::TestCase expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n} expected << %{<input type="hidden" id="post_updated_at_2i" name="post[updated_at(2i)]" value="6" />\n} - expected << %{<input type="hidden" id="post_updated_at_3i" name="post[updated_at(3i)]" value="15" />\n} + expected << %{<input type="hidden" id="post_updated_at_3i" name="post[updated_at(3i)]" value="1" />\n} expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n} 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) } @@ -2467,7 +2493,7 @@ class DateHelperTest < ActionView::TestCase expected = %{<input type="hidden" id="post_updated_at_1i" disabled="disabled" name="post[updated_at(1i)]" value="2004" />\n} expected << %{<input type="hidden" id="post_updated_at_2i" disabled="disabled" name="post[updated_at(2i)]" value="6" />\n} - expected << %{<input type="hidden" id="post_updated_at_3i" disabled="disabled" name="post[updated_at(3i)]" value="15" />\n} + expected << %{<input type="hidden" id="post_updated_at_3i" disabled="disabled" name="post[updated_at(3i)]" value="1" />\n} expected << %{<select id="post_updated_at_4i" disabled="disabled" name="post[updated_at(4i)]">\n} 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) } @@ -2865,6 +2891,10 @@ class DateHelperTest < ActionView::TestCase assert_match(/<time.*>Right now<\/time>/, time_tag(Time.now, 'Right now')) end + def test_time_tag_with_given_block + assert_match(/<time.*><span>Right now<\/span><\/time>/, time_tag(Time.now){ '<span>Right now</span>'.html_safe }) + end + def test_time_tag_with_different_format time = Time.now expected = "<time datetime=\"#{time.xmlschema}\">#{I18n.l(time, :format => :short)}</time>" diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 3546bd3bee..f13296a175 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -249,35 +249,35 @@ class FormHelperTest < ActionView::TestCase end def test_label_with_block_in_erb - assert_equal "<label for=\"post_message\">\n Message\n <input id=\"post_message\" name=\"post[message]\" size=\"30\" type=\"text\" />\n</label>", view.render("test/label_with_block") + assert_equal "<label for=\"post_message\">\n Message\n <input id=\"post_message\" name=\"post[message]\" type=\"text\" />\n</label>", view.render("test/label_with_block") end def test_text_field assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title") + '<input id="post_title" name="post[title]" type="text" value="Hello World" />', text_field("post", "title") ) assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="password" />', password_field("post", "title") + '<input id="post_title" name="post[title]" type="password" />', password_field("post", "title") ) assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="password" value="Hello World" />', password_field("post", "title", :value => @post.title) + '<input id="post_title" name="post[title]" type="password" value="Hello World" />', password_field("post", "title", :value => @post.title) ) assert_dom_equal( - '<input id="person_name" name="person[name]" size="30" type="password" />', password_field("person", "name") + '<input id="person_name" name="person[name]" type="password" />', password_field("person", "name") ) end def test_text_field_with_escapes @post.title = "<b>Hello World</b>" assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="<b>Hello World</b>" />', text_field("post", "title") + '<input id="post_title" name="post[title]" type="text" value="<b>Hello World</b>" />', text_field("post", "title") ) end def test_text_field_with_html_entities @post.title = "The HTML Entity for & is &" assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="The HTML Entity for & is &amp;" />', + '<input id="post_title" name="post[title]" type="text" value="The HTML Entity for & is &amp;" />', text_field("post", "title") ) end @@ -301,18 +301,18 @@ class FormHelperTest < ActionView::TestCase end def test_text_field_with_nil_value - expected = '<input id="post_title" name="post[title]" size="30" type="text" />' + expected = '<input id="post_title" name="post[title]" type="text" />' assert_dom_equal expected, text_field("post", "title", :value => nil) end def test_text_field_with_nil_name - expected = '<input id="post_title" size="30" type="text" value="Hello World" />' + expected = '<input id="post_title" type="text" value="Hello World" />' assert_dom_equal expected, text_field("post", "title", :name => nil) end def test_text_field_doesnt_change_param_values object_name = 'post[]' - expected = '<input id="post_123_title" name="post[123][title]" size="30" type="text" value="Hello World" />' + expected = '<input id="post_123_title" name="post[123][title]" type="text" value="Hello World" />' assert_equal expected, text_field(object_name, "title") assert_equal object_name, "post[]" end @@ -346,7 +346,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_field_with_custom_type - assert_dom_equal '<input id="user_email" size="30" name="user[email]" type="email" />', + assert_dom_equal '<input id="user_email" name="user[email]" type="email" />', text_field("user", "email", :type => "email") end @@ -387,6 +387,11 @@ class FormHelperTest < ActionView::TestCase ) end + def test_check_box_with_include_hidden_false + @post.secret = false + assert_dom_equal('<input id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret", :include_hidden => false)) + end + def test_check_box_with_explicit_checked_and_unchecked_values @post.secret = "on" assert_dom_equal( @@ -474,7 +479,7 @@ class FormHelperTest < ActionView::TestCase def test_text_area assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Back to the hill and over it again!</textarea>', + %{<textarea id="post_body" name="post[body]">\nBack to the hill and over it again!</textarea>}, text_area("post", "body") ) end @@ -482,14 +487,14 @@ class FormHelperTest < ActionView::TestCase def test_text_area_with_escapes @post.body = "Back to <i>the</i> hill and over it again!" assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Back to <i>the</i> hill and over it again!</textarea>', + %{<textarea id="post_body" name="post[body]">\nBack to <i>the</i> hill and over it again!</textarea>}, text_area("post", "body") ) end def test_text_area_with_alternate_value assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Testing alternate values.</textarea>', + %{<textarea id="post_body" name="post[body]">\nTesting alternate values.</textarea>}, text_area("post", "body", :value => 'Testing alternate values.') ) end @@ -497,25 +502,25 @@ class FormHelperTest < ActionView::TestCase def test_text_area_with_html_entities @post.body = "The HTML Entity for & is &" assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">The HTML Entity for & is &amp;</textarea>', + %{<textarea id="post_body" name="post[body]">\nThe HTML Entity for & is &amp;</textarea>}, text_area("post", "body") ) end def test_text_area_with_size_option assert_dom_equal( - '<textarea cols="183" id="post_body" name="post[body]" rows="820">Back to the hill and over it again!</textarea>', + %{<textarea cols="183" id="post_body" name="post[body]" rows="820">\nBack to the hill and over it again!</textarea>}, text_area("post", "body", :size => "183x820") ) end def test_search_field - expected = %{<input id="contact_notes_query" size="30" name="contact[notes_query]" type="search" />} + expected = %{<input id="contact_notes_query" name="contact[notes_query]" type="search" />} assert_dom_equal(expected, search_field("contact", "notes_query")) end def test_telephone_field - expected = %{<input id="user_cell" size="30" name="user[cell]" type="tel" />} + expected = %{<input id="user_cell" name="user[cell]" type="tel" />} assert_dom_equal(expected, telephone_field("user", "cell")) end @@ -546,12 +551,12 @@ class FormHelperTest < ActionView::TestCase end def test_url_field - expected = %{<input id="user_homepage" size="30" name="user[homepage]" type="url" />} + expected = %{<input id="user_homepage" name="user[homepage]" type="url" />} assert_dom_equal(expected, url_field("user", "homepage")) end def test_email_field - expected = %{<input id="user_address" size="30" name="user[address]" type="email" />} + expected = %{<input id="user_address" name="user[address]" type="email" />} assert_dom_equal(expected, email_field("user", "address")) end @@ -571,10 +576,10 @@ class FormHelperTest < ActionView::TestCase def test_explicit_name assert_dom_equal( - '<input id="post_title" name="dont guess" size="30" type="text" value="Hello World" />', text_field("post", "title", "name" => "dont guess") + '<input id="post_title" name="dont guess" type="text" value="Hello World" />', text_field("post", "title", "name" => "dont guess") ) assert_dom_equal( - '<textarea cols="40" id="post_body" name="really!" rows="20">Back to the hill and over it again!</textarea>', + %{<textarea id="post_body" name="really!">\nBack to the hill and over it again!</textarea>}, text_area("post", "body", "name" => "really!") ) assert_dom_equal( @@ -591,10 +596,10 @@ class FormHelperTest < ActionView::TestCase def test_explicit_id assert_dom_equal( - '<input id="dont guess" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title", "id" => "dont guess") + '<input id="dont guess" name="post[title]" type="text" value="Hello World" />', text_field("post", "title", "id" => "dont guess") ) assert_dom_equal( - '<textarea cols="40" id="really!" name="post[body]" rows="20">Back to the hill and over it again!</textarea>', + %{<textarea id="really!" name="post[body]">\nBack to the hill and over it again!</textarea>}, text_area("post", "body", "id" => "really!") ) assert_dom_equal( @@ -611,10 +616,10 @@ class FormHelperTest < ActionView::TestCase def test_nil_id assert_dom_equal( - '<input name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title", "id" => nil) + '<input name="post[title]" type="text" value="Hello World" />', text_field("post", "title", "id" => nil) ) assert_dom_equal( - '<textarea cols="40" name="post[body]" rows="20">Back to the hill and over it again!</textarea>', + %{<textarea name="post[body]">\nBack to the hill and over it again!</textarea>}, text_area("post", "body", "id" => nil) ) assert_dom_equal( @@ -641,11 +646,11 @@ class FormHelperTest < ActionView::TestCase def test_index assert_dom_equal( - '<input name="post[5][title]" size="30" id="post_5_title" type="text" value="Hello World" />', + '<input name="post[5][title]" id="post_5_title" type="text" value="Hello World" />', text_field("post", "title", "index" => 5) ) assert_dom_equal( - '<textarea cols="40" name="post[5][body]" id="post_5_body" rows="20">Back to the hill and over it again!</textarea>', + %{<textarea name="post[5][body]" id="post_5_body">\nBack to the hill and over it again!</textarea>}, text_area("post", "body", "index" => 5) ) assert_dom_equal( @@ -668,11 +673,11 @@ class FormHelperTest < ActionView::TestCase def test_index_with_nil_id assert_dom_equal( - '<input name="post[5][title]" size="30" type="text" value="Hello World" />', + '<input name="post[5][title]" type="text" value="Hello World" />', text_field("post", "title", "index" => 5, 'id' => nil) ) assert_dom_equal( - '<textarea cols="40" name="post[5][body]" rows="20">Back to the hill and over it again!</textarea>', + %{<textarea name="post[5][body]">\nBack to the hill and over it again!</textarea>}, text_area("post", "body", "index" => 5, 'id' => nil) ) assert_dom_equal( @@ -700,10 +705,10 @@ class FormHelperTest < ActionView::TestCase label("post[]", "title") ) assert_dom_equal( - "<input id=\"post_#{pid}_title\" name=\"post[#{pid}][title]\" size=\"30\" type=\"text\" value=\"Hello World\" />", text_field("post[]","title") + "<input id=\"post_#{pid}_title\" name=\"post[#{pid}][title]\" type=\"text\" value=\"Hello World\" />", text_field("post[]","title") ) assert_dom_equal( - "<textarea cols=\"40\" id=\"post_#{pid}_body\" name=\"post[#{pid}][body]\" rows=\"20\">Back to the hill and over it again!</textarea>", + "<textarea id=\"post_#{pid}_body\" name=\"post[#{pid}][body]\">\nBack to the hill and over it again!</textarea>", text_area("post[]", "body") ) assert_dom_equal( @@ -711,7 +716,7 @@ class FormHelperTest < ActionView::TestCase check_box("post[]", "secret") ) assert_dom_equal( -"<input checked=\"checked\" id=\"post_#{pid}_title_hello_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Hello World\" />", + "<input checked=\"checked\" id=\"post_#{pid}_title_hello_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Hello World\" />", radio_button("post[]", "title", "Hello World") ) assert_dom_equal("<input id=\"post_#{pid}_title_goodbye_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Goodbye World\" />", @@ -722,11 +727,11 @@ class FormHelperTest < ActionView::TestCase def test_auto_index_with_nil_id pid = 123 assert_dom_equal( - "<input name=\"post[#{pid}][title]\" size=\"30\" type=\"text\" value=\"Hello World\" />", + "<input name=\"post[#{pid}][title]\" type=\"text\" value=\"Hello World\" />", text_field("post[]","title", :id => nil) ) assert_dom_equal( - "<textarea cols=\"40\" name=\"post[#{pid}][body]\" rows=\"20\">Back to the hill and over it again!</textarea>", + "<textarea name=\"post[#{pid}][body]\">\nBack to the hill and over it again!</textarea>", text_area("post[]", "body", :id => nil) ) assert_dom_equal( @@ -760,8 +765,8 @@ class FormHelperTest < ActionView::TestCase expected = whole_form("/posts/123", "create-post" , "edit_post", :method => 'patch') do "<label for='post_title'>The Title</label>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + "<input name='commit' type='submit' value='Create post' />" + @@ -771,6 +776,44 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_form_for_with_collection_radio_buttons + post = Post.new + def post.active; false; end + form_for(post) do |f| + concat f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) + end + + expected = whole_form("/posts", "new_post" , "new_post") do + "<input id='post_active_true' name='post[active]' type='radio' value='true' />" + + "<label for='post_active_true'>true</label>" + + "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" + + "<label for='post_active_false'>false</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_for_with_collection_check_boxes + post = Post.new + def post.tag_ids; [1, 3]; end + collection = (1..3).map{|i| [i, "Tag #{i}"] } + form_for(post) do |f| + concat f.collection_check_boxes(:tag_ids, collection, :first, :last) + end + + expected = whole_form("/posts", "new_post" , "new_post") do + "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" + + "<label for='post_tag_ids_1'>Tag 1</label>" + + "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" + + "<label for='post_tag_ids_2'>Tag 2</label>" + + "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" + + "<label for='post_tag_ids_3'>Tag 3</label>" + + "<input name='post[tag_ids][]' type='hidden' value='' />" + end + + assert_dom_equal expected, output_buffer + end + def test_form_for_with_file_field_generate_multipart Post.send :attr_accessor, :file @@ -821,7 +864,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts/44", "edit_post_44" , "edit_post", :method => 'patch') do - "<input name='post[title]' size='30' type='text' id='post_title' value='And his name will be forty and four.' />" + + "<input name='post[title]' type='text' id='post_title' value='And his name will be forty and four.' />" + "<input name='commit' type='submit' value='Edit post' />" end @@ -839,8 +882,8 @@ class FormHelperTest < ActionView::TestCase expected = whole_form("/posts/123", "create-post", "edit_other_name", :method => 'patch') do "<label for='other_name_title' class='post_title'>Title</label>" + - "<input name='other_name[title]' size='30' id='other_name_title' value='Hello World' type='text' />" + - "<textarea name='other_name[body]' id='other_name_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='other_name[title]' id='other_name_title' value='Hello World' type='text' />" + + "<textarea name='other_name[body]' id='other_name_body'>\nBack to the hill and over it again!</textarea>" + "<input name='other_name[secret]' value='0' type='hidden' />" + "<input name='other_name[secret]' checked='checked' id='other_name_secret' value='1' type='checkbox' />" + "<input name='commit' value='Create post' type='submit' />" @@ -857,8 +900,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/", "create-post", "edit_post", "delete") do - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" end @@ -874,8 +917,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/", "create-post", "edit_post", "delete") do - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" end @@ -891,7 +934,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/search", "search-post", "new_post", "get") do - "<input name='post[title]' size='30' type='search' id='post_title' />" + "<input name='post[title]' type='search' id='post_title' />" end assert_dom_equal expected, output_buffer @@ -905,8 +948,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/", "create-post", "edit_post", :method => 'patch', :remote => true) do - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" end @@ -922,8 +965,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/", "create-post", "edit_post", :method => 'patch', :remote => true) do - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" end @@ -941,8 +984,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts", 'new_post', 'new_post', :remote => true) do - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" end @@ -958,8 +1001,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/", "create-post") do - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" end @@ -977,8 +1020,8 @@ class FormHelperTest < ActionView::TestCase expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'patch') do "<label for='post_123_title'>Title</label>" + - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" + + "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[123][secret]' type='hidden' value='0' />" + "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" end @@ -994,8 +1037,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'patch') do - "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" + - "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[][title]' type='text' id='post__title' value='Hello World' />" + + "<textarea name='post[][body]' id='post__body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[][secret]' type='hidden' value='0' />" + "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" end @@ -1003,6 +1046,54 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_form_for_label_error_wrapping + form_for(@post) do |f| + concat f.label(:author_name, :class => 'label') + concat f.text_field(:author_name) + concat f.submit('Create post') + end + + expected = whole_form('/posts/123', 'edit_post_123' , 'edit_post', 'patch') do + "<div class='field_with_errors'><label for='post_author_name' class='label'>Author name</label></div>" + + "<div class='field_with_errors'><input name='post[author_name]' type='text' id='post_author_name' value='' /></div>" + + "<input name='commit' type='submit' value='Create post' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_for_label_error_wrapping_without_conventional_instance_variable + post = remove_instance_variable :@post + + form_for(post) do |f| + concat f.label(:author_name, :class => 'label') + concat f.text_field(:author_name) + concat f.submit('Create post') + end + + expected = whole_form('/posts/123', 'edit_post_123' , 'edit_post', 'patch') do + "<div class='field_with_errors'><label for='post_author_name' class='label'>Author name</label></div>" + + "<div class='field_with_errors'><input name='post[author_name]' type='text' id='post_author_name' value='' /></div>" + + "<input name='commit' type='submit' value='Create post' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_for_label_error_wrapping_block_and_non_block_versions + form_for(@post) do |f| + concat f.label(:author_name, 'Name', :class => 'label') + concat f.label(:author_name, :class => 'label') { 'Name' } + end + + expected = whole_form('/posts/123', 'edit_post_123' , 'edit_post', 'patch') do + "<div class='field_with_errors'><label for='post_author_name' class='label'>Name</label></div>" + + "<div class='field_with_errors'><label for='post_author_name' class='label'>Name</label></div>" + end + + assert_dom_equal expected, output_buffer + end + def test_form_for_with_namespace form_for(@post, :namespace => 'namespace') do |f| concat f.text_field(:title) @@ -1011,8 +1102,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'patch') do - "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" + - "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" + + "<textarea name='post[body]' id='namespace_post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='namespace_post_secret' value='1' />" end @@ -1020,6 +1111,14 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_form_for_with_namespace_with_date_select + form_for(@post, :namespace => 'namespace') do |f| + concat f.date_select(:written_on) + end + + assert_select 'select#namespace_post_written_on_1i' + end + def test_form_for_with_namespace_with_label form_for(@post, :namespace => 'namespace') do |f| concat f.label(:title) @@ -1028,7 +1127,7 @@ class FormHelperTest < ActionView::TestCase expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'patch') do "<label for='namespace_post_title'>Title</label>" + - "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" + "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" end assert_dom_equal expected, output_buffer @@ -1042,7 +1141,7 @@ class FormHelperTest < ActionView::TestCase expected_1 = whole_form('/posts/123', 'namespace_1_edit_post_123', 'edit_post', 'patch') do "<label for='namespace_1_post_title'>Title</label>" + - "<input name='post[title]' size='30' type='text' id='namespace_1_post_title' value='Hello World' />" + "<input name='post[title]' type='text' id='namespace_1_post_title' value='Hello World' />" end assert_dom_equal expected_1, output_buffer @@ -1054,7 +1153,7 @@ class FormHelperTest < ActionView::TestCase expected_2 = whole_form('/posts/123', 'namespace_2_edit_post_123', 'edit_post', 'patch') do "<label for='namespace_2_post_title'>Title</label>" + - "<input name='post[title]' size='30' type='text' id='namespace_2_post_title' value='Hello World' />" + "<input name='post[title]' type='text' id='namespace_2_post_title' value='Hello World' />" end assert_dom_equal expected_2, output_buffer @@ -1071,9 +1170,9 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'patch') do - "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" + - "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[comment][body]' size='30' type='text' id='namespace_post_comment_body' value='Hello World' />" + "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" + + "<textarea name='post[body]' id='namespace_post_body'>\nBack to the hill and over it again!</textarea>" + + "<input name='post[comment][body]' type='text' id='namespace_post_comment_body' value='Hello World' />" end assert_dom_equal expected, output_buffer @@ -1154,7 +1253,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - "<input name='post[comment][body]' size='30' type='text' id='post_comment_body' value='Hello World' />" + "<input name='post[comment][body]' type='text' id='post_comment_body' value='Hello World' />" end assert_dom_equal expected, output_buffer @@ -1169,8 +1268,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'patch') do - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<input name='post[123][comment][][name]' size='30' type='text' id='post_123_comment__name' value='new comment' />" + "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" + + "<input name='post[123][comment][][name]' type='text' id='post_123_comment__name' value='new comment' />" end assert_dom_equal expected, output_buffer @@ -1185,8 +1284,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'patch') do - "<input name='post[1][title]' size='30' type='text' id='post_1_title' value='Hello World' />" + - "<input name='post[1][comment][1][name]' size='30' type='text' id='post_1_comment_1_name' value='new comment' />" + "<input name='post[1][title]' type='text' id='post_1_title' value='Hello World' />" + + "<input name='post[1][comment][1][name]' type='text' id='post_1_comment_1_name' value='new comment' />" end assert_dom_equal expected, output_buffer @@ -1200,7 +1299,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'patch') do - "<input name='post[1][comment][title]' size='30' type='text' id='post_1_comment_title' value='Hello World' />" + "<input name='post[1][comment][title]' type='text' id='post_1_comment_title' value='Hello World' />" end assert_dom_equal expected, output_buffer @@ -1214,7 +1313,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'patch') do - "<input name='post[1][comment][5][title]' size='30' type='text' id='post_1_comment_5_title' value='Hello World' />" + "<input name='post[1][comment][5][title]' type='text' id='post_1_comment_5_title' value='Hello World' />" end assert_dom_equal expected, output_buffer @@ -1228,7 +1327,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'patch') do - "<input name='post[123][comment][title]' size='30' type='text' id='post_123_comment_title' value='Hello World' />" + "<input name='post[123][comment][title]' type='text' id='post_123_comment_title' value='Hello World' />" end assert_dom_equal expected, output_buffer @@ -1256,7 +1355,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'patch') do - "<input name='post[123][comment][123][title]' size='30' type='text' id='post_123_comment_123_title' value='Hello World' />" + "<input name='post[123][comment][123][title]' type='text' id='post_123_comment_123_title' value='Hello World' />" end assert_dom_equal expected, output_buffer @@ -1276,9 +1375,9 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'patch') do - "<input name='post[123][comment][5][title]' size='30' type='text' id='post_123_comment_5_title' value='Hello World' />" + "<input name='post[123][comment][5][title]' type='text' id='post_123_comment_5_title' value='Hello World' />" end + whole_form('/posts/123', 'edit_post', 'edit_post', 'patch') do - "<input name='post[1][comment][123][title]' size='30' type='text' id='post_1_comment_123_title' value='Hello World' />" + "<input name='post[1][comment][123][title]' type='text' id='post_1_comment_123_title' value='Hello World' />" end assert_dom_equal expected, output_buffer @@ -1295,8 +1394,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="new author" />' + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="new author" />' end assert_dom_equal expected, output_buffer @@ -1322,8 +1421,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' end @@ -1341,8 +1440,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' end @@ -1360,8 +1459,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' end assert_dom_equal expected, output_buffer @@ -1378,8 +1477,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' end assert_dom_equal expected, output_buffer @@ -1396,8 +1495,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' end @@ -1416,9 +1515,9 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' end assert_dom_equal expected, output_buffer @@ -1437,10 +1536,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -1464,11 +1563,11 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' end assert_dom_equal expected, output_buffer @@ -1491,10 +1590,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' end assert_dom_equal expected, output_buffer @@ -1517,11 +1616,11 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' end assert_dom_equal expected, output_buffer @@ -1540,10 +1639,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -1564,11 +1663,11 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' end assert_dom_equal expected, output_buffer @@ -1587,9 +1686,9 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="new comment" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="new comment" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />' end assert_dom_equal expected, output_buffer @@ -1608,10 +1707,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />' end assert_dom_equal expected, output_buffer @@ -1626,7 +1725,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' end assert_dom_equal expected, output_buffer @@ -1643,10 +1742,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -1664,10 +1763,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -1686,10 +1785,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -1709,10 +1808,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />' end assert_dom_equal expected, output_buffer @@ -1729,7 +1828,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" size="30" type="text" value="comment #321" />' + + '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" type="text" value="comment #321" />' + '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />' end @@ -1765,16 +1864,16 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" size="30" type="text" value="commentrelevance #314" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' + + '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" type="text" value="commentrelevance #314" />' + '<input id="post_comments_attributes_0_relevances_attributes_0_id" name="post[comments_attributes][0][relevances_attributes][0][id]" type="hidden" value="314" />' + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_tags_attributes_0_value" name="post[tags_attributes][0][value]" size="30" type="text" value="tag #123" />' + - '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" size="30" type="text" value="tagrelevance #3141" />' + + '<input id="post_tags_attributes_0_value" name="post[tags_attributes][0][value]" type="text" value="tag #123" />' + + '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" type="text" value="tagrelevance #3141" />' + '<input id="post_tags_attributes_0_relevances_attributes_0_id" name="post[tags_attributes][0][relevances_attributes][0][id]" type="hidden" value="3141" />' + '<input id="post_tags_attributes_0_id" name="post[tags_attributes][0][id]" type="hidden" value="123" />' + - '<input id="post_tags_attributes_1_value" name="post[tags_attributes][1][value]" size="30" type="text" value="tag #456" />' + - '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" size="30" type="text" value="tagrelevance #31415" />' + + '<input id="post_tags_attributes_1_value" name="post[tags_attributes][1][value]" type="text" value="tag #456" />' + + '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" type="text" value="tagrelevance #31415" />' + '<input id="post_tags_attributes_1_relevances_attributes_0_id" name="post[tags_attributes][1][relevances_attributes][0][id]" type="hidden" value="31415" />' + '<input id="post_tags_attributes_1_id" name="post[tags_attributes][1][id]" type="hidden" value="456" />' end @@ -1792,7 +1891,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="hash backed author" />' + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="hash backed author" />' end assert_dom_equal expected, output_buffer @@ -1806,8 +1905,8 @@ class FormHelperTest < ActionView::TestCase end expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" @@ -1822,8 +1921,8 @@ class FormHelperTest < ActionView::TestCase end expected = - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" + + "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[123][secret]' type='hidden' value='0' />" + "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" @@ -1838,8 +1937,8 @@ class FormHelperTest < ActionView::TestCase end expected = - "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" + - "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[][title]' type='text' id='post__title' value='Hello World' />" + + "<textarea name='post[][body]' id='post__body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[][secret]' type='hidden' value='0' />" + "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" @@ -1854,8 +1953,8 @@ class FormHelperTest < ActionView::TestCase end expected = - "<input name='post[abc][title]' size='30' type='text' id='post_abc_title' value='Hello World' />" + - "<textarea name='post[abc][body]' id='post_abc_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[abc][title]' type='text' id='post_abc_title' value='Hello World' />" + + "<textarea name='post[abc][body]' id='post_abc_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[abc][secret]' type='hidden' value='0' />" + "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />" @@ -1870,8 +1969,8 @@ class FormHelperTest < ActionView::TestCase end expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" @@ -1886,8 +1985,8 @@ class FormHelperTest < ActionView::TestCase end expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" @@ -1901,7 +2000,7 @@ class FormHelperTest < ActionView::TestCase end assert_dom_equal "<label for=\"author_post_title\">Title</label>" + - "<input name='author[post][title]' size='30' type='text' id='author_post_title' value='Hello World' />", + "<input name='author[post][title]' type='text' id='author_post_title' value='Hello World' />", output_buffer end @@ -1912,7 +2011,7 @@ class FormHelperTest < ActionView::TestCase end assert_dom_equal "<label for=\"author_post_1_title\">Title</label>" + - "<input name='author[post][1][title]' size='30' type='text' id='author_post_1_title' value='Hello World' />", + "<input name='author[post][1][title]' type='text' id='author_post_1_title' value='Hello World' />", output_buffer end @@ -1931,8 +2030,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'create-post', 'edit_post', :method => 'patch') do - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='parent_post[secret]' type='hidden' value='0' />" + "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />" end @@ -1951,9 +2050,9 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'create-post', 'edit_post', :method => 'patch') do - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' size='30' />" + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + + "<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' />" end assert_dom_equal expected, output_buffer @@ -1967,7 +2066,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'patch') do - "<input name='post[category][name]' type='text' size='30' id='post_category_name' />" + "<input name='post[category][name]' type='text' id='post_category_name' />" end assert_dom_equal expected, output_buffer @@ -1991,45 +2090,14 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + + "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" + + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" end assert_dom_equal expected, output_buffer end - def hidden_fields(method = nil) - txt = %{<div style="margin:0;padding:0;display:inline">} - txt << %{<input name="utf8" type="hidden" value="✓" />} - if method && !method.to_s.in?(['get', 'post']) - txt << %{<input name="_method" type="hidden" value="#{method}" />} - end - txt << %{</div>} - end - - def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) - txt = %{<form accept-charset="UTF-8" action="#{action}"} - txt << %{ enctype="multipart/form-data"} if multipart - txt << %{ data-remote="true"} if remote - txt << %{ class="#{html_class}"} if html_class - txt << %{ id="#{id}"} if id - method = method.to_s == "get" ? "get" : "post" - txt << %{ method="#{method}">} - end - - def whole_form(action = "/", id = nil, html_class = nil, options = nil) - contents = block_given? ? yield : "" - - if options.is_a?(Hash) - method, remote, multipart = options.values_at(:method, :remote, :multipart) - else - method = options - end - - form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>" - end - def test_default_form_builder old_default_form_builder, ActionView::Base.default_form_builder = ActionView::Base.default_form_builder, LabelledFormBuilder @@ -2041,8 +2109,8 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + + "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" + + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" end @@ -2059,8 +2127,8 @@ class FormHelperTest < ActionView::TestCase end expected = - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + + "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" + + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" assert_dom_equal expected, output_buffer @@ -2211,8 +2279,51 @@ class FormHelperTest < ActionView::TestCase assert_equal "fields", output end + def test_form_builder_block_argument_deprecation + builder_class = Class.new(ActionView::Helpers::FormBuilder) do + def initialize(object_name, object, template, options, block) + super + end + end + + assert_deprecated(/Giving a block to FormBuilder is deprecated and has no effect anymore/) do + builder_class.new(:foo, nil, nil, {}, proc {}) + end + end + protected + def hidden_fields(method = nil) + txt = %{<div style="margin:0;padding:0;display:inline">} + txt << %{<input name="utf8" type="hidden" value="✓" />} + if method && !method.to_s.in?(['get', 'post']) + txt << %{<input name="_method" type="hidden" value="#{method}" />} + end + txt << %{</div>} + end + + def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) + txt = %{<form accept-charset="UTF-8" action="#{action}"} + txt << %{ enctype="multipart/form-data"} if multipart + txt << %{ data-remote="true"} if remote + txt << %{ class="#{html_class}"} if html_class + txt << %{ id="#{id}"} if id + method = method.to_s == "get" ? "get" : "post" + txt << %{ method="#{method}">} + end + + def whole_form(action = "/", id = nil, html_class = nil, options = nil) + contents = block_given? ? yield : "" + + if options.is_a?(Hash) + method, remote, multipart = options.values_at(:method, :remote, :multipart) + else + method = options + end + + form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>" + end + def protect_against_forgery? false end diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb index 6b8d62df62..2c0da8473a 100644 --- a/actionpack/test/template/form_options_helper_test.rb +++ b/actionpack/test/template/form_options_helper_test.rb @@ -509,7 +509,7 @@ class FormOptionsHelperTest < ActionView::TestCase def test_select_under_fields_for_with_string_and_given_prompt @post = Post.new - options = "<option value=\"abe\">abe</option><option value=\"mus\">mus</option><option value=\"hest\">hest</option>" + options = "<option value=\"abe\">abe</option><option value=\"mus\">mus</option><option value=\"hest\">hest</option>".html_safe output_buffer = fields_for :post, @post do |f| concat f.select(:category, options, :prompt => 'The prompt') @@ -529,6 +529,14 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_select_with_multiple_and_without_hidden_input + output_buffer = select(:post, :category, "", {:include_hidden => false}, :multiple => true) + assert_dom_equal( + "<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>", + output_buffer + ) + end + def test_select_with_multiple_and_disabled_to_add_disabled_hidden_input output_buffer = select(:post, :category, "", {}, :multiple => true, :disabled => true) assert_dom_equal( @@ -665,6 +673,13 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_select_escapes_options + assert_dom_equal( + '<select id="post_title" name="post[title]"><script>alert(1)</script></select>', + select('post', 'title', '<script>alert(1)</script>') + ) + end + def test_select_with_selected_nil @post = Post.new @post.category = "<mus>" diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index 6ef4cf4dd2..1e92ff99ff 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -222,19 +222,19 @@ class FormTagHelperTest < ActionView::TestCase def test_text_area_tag_size_string actual = text_area_tag "body", "hello world", "size" => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>) + expected = %(<textarea cols="20" id="body" name="body" rows="40">\nhello world</textarea>) assert_dom_equal expected, actual end def test_text_area_tag_size_symbol actual = text_area_tag "body", "hello world", :size => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>) + expected = %(<textarea cols="20" id="body" name="body" rows="40">\nhello world</textarea>) assert_dom_equal expected, actual end def test_text_area_tag_should_disregard_size_if_its_given_as_an_integer actual = text_area_tag "body", "hello world", :size => 20 - expected = %(<textarea id="body" name="body">hello world</textarea>) + expected = %(<textarea id="body" name="body">\nhello world</textarea>) assert_dom_equal expected, actual end @@ -245,19 +245,19 @@ class FormTagHelperTest < ActionView::TestCase def test_text_area_tag_escape_content actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40"><b>hello world</b></textarea>) + expected = %(<textarea cols="20" id="body" name="body" rows="40">\n<b>hello world</b></textarea>) assert_dom_equal expected, actual end def test_text_area_tag_unescaped_content actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40", :escape => false - expected = %(<textarea cols="20" id="body" name="body" rows="40"><b>hello world</b></textarea>) + expected = %(<textarea cols="20" id="body" name="body" rows="40">\n<b>hello world</b></textarea>) assert_dom_equal expected, actual end def test_text_area_tag_unescaped_nil_content actual = text_area_tag "body", nil, :escape => false - expected = %(<textarea id="body" name="body"></textarea>) + expected = %(<textarea id="body" name="body">\n</textarea>) assert_dom_equal expected, actual end @@ -513,6 +513,16 @@ class FormTagHelperTest < ActionView::TestCase expected = %(<fieldset class="format">Hello world!</fieldset>) assert_dom_equal expected, output_buffer + + output_buffer = render_erb("<%= field_set_tag %>") + + expected = %(<fieldset></fieldset>) + assert_dom_equal expected, output_buffer + + output_buffer = render_erb("<%= field_set_tag('You legend!') %>") + + expected = %(<fieldset><legend>You legend!</legend></fieldset>) + assert_dom_equal expected, output_buffer end def test_text_area_tag_options_symbolize_keys_side_effects diff --git a/actionpack/test/template/html-scanner/sanitizer_test.rb b/actionpack/test/template/html-scanner/sanitizer_test.rb index 32c655c5fd..324caef224 100644 --- a/actionpack/test/template/html-scanner/sanitizer_test.rb +++ b/actionpack/test/template/html-scanner/sanitizer_test.rb @@ -125,6 +125,24 @@ class SanitizerTest < ActionController::TestCase assert_equal(text, sanitizer.sanitize(text, :attributes => ['foo'])) end + def test_should_raise_argument_error_if_tags_is_not_enumerable + sanitizer = HTML::WhiteListSanitizer.new + e = assert_raise(ArgumentError) do + sanitizer.sanitize('', :tags => 'foo') + end + + assert_equal "You should pass :tags as an Enumerable", e.message + end + + def test_should_raise_argument_error_if_attributes_is_not_enumerable + sanitizer = HTML::WhiteListSanitizer.new + e = assert_raise(ArgumentError) do + sanitizer.sanitize('', :attributes => 'foo') + end + + assert_equal "You should pass :attributes as an Enumerable", e.message + end + [%w(img src), %w(a href)].each do |(tag, attr)| define_method "test_should_strip_#{attr}_attribute_in_#{tag}_with_bad_protocols" do assert_sanitized %(<#{tag} #{attr}="javascript:bang" title="1">boo</#{tag}>), %(<#{tag} title="1">boo</#{tag}>) diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb index 9441bd6b38..64898f7ad1 100644 --- a/actionpack/test/template/javascript_helper_test.rb +++ b/actionpack/test/template/javascript_helper_test.rb @@ -28,6 +28,8 @@ class JavaScriptHelperTest < ActionView::TestCase assert_equal %(backslash\\\\test), escape_javascript( %(backslash\\test) ) assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags)) assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\250 newline).force_encoding('UTF-8').encode!) + assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\251 newline).force_encoding('UTF-8').encode!) + assert_equal %(dont <\\/close> tags), j(%(dont </close> tags)) end diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index 482d953907..5c6f23d70b 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -96,6 +96,7 @@ class NumberHelperTest < ActionView::TestCase assert_equal("0.001", number_with_precision(0.00111, :precision => 3)) assert_equal("10.00", number_with_precision(9.995, :precision => 2)) assert_equal("11.00", number_with_precision(10.995, :precision => 2)) + assert_equal("0.00", number_with_precision(-0.001, :precision => 2)) end def test_number_with_precision_with_custom_delimiter_and_separator diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index 7347e15373..122b07d348 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -238,6 +238,10 @@ module RenderTestCases def test_render_partial_with_nil_values_in_collection assert_equal "Hello: davidHello: Anonymous", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), nil ]) end + + def test_render_partial_with_layout_using_collection_and_template + assert_equal "<b>Hello: Amazon</b><b>Hello: Yahoo</b>", @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial', :collection => [ Customer.new("Amazon"), Customer.new("Yahoo") ]) + end def test_render_partial_with_empty_array_should_return_nil assert_nil @view.render(:partial => []) diff --git a/actionpack/test/template/sprockets_helper_test.rb b/actionpack/test/template/sprockets_helper_test.rb deleted file mode 100644 index 1c591bdcc2..0000000000 --- a/actionpack/test/template/sprockets_helper_test.rb +++ /dev/null @@ -1,348 +0,0 @@ -require 'abstract_unit' -require 'sprockets' -require 'sprockets/helpers/rails_helper' -require 'mocha' - -class SprocketsHelperTest < ActionView::TestCase - include Sprockets::Helpers::RailsHelper - - attr_accessor :assets - - class MockRequest - def protocol() 'http://' end - def ssl?() false end - def host_with_port() 'localhost' end - end - - def setup - super - - @controller = BasicController.new - @controller.request = MockRequest.new - - @assets = Sprockets::Environment.new - @assets.append_path(FIXTURES.join("sprockets/app/javascripts")) - @assets.append_path(FIXTURES.join("sprockets/app/stylesheets")) - @assets.append_path(FIXTURES.join("sprockets/app/images")) - @assets.append_path(FIXTURES.join("sprockets/app/fonts")) - - application = Struct.new(:config, :assets).new(config, @assets) - Rails.stubs(:application).returns(application) - @config = config - @config.perform_caching = true - @config.assets.digest = true - @config.assets.compile = true - end - - def url_for(*args) - "http://www.example.com" - end - - def config - @controller ? @controller.config : @config - end - - def compute_host(source, request, options = {}) - raise "Should never get here" - end - - test "asset_path" do - assert_match %r{/assets/logo-[0-9a-f]+.png}, - asset_path("logo.png") - assert_match %r{/assets/logo-[0-9a-f]+.png}, - asset_path("logo.png", :digest => true) - assert_match %r{/assets/logo.png}, - asset_path("logo.png", :digest => false) - end - - test "custom_asset_path" do - @config.assets.prefix = '/s' - assert_match %r{/s/logo-[0-9a-f]+.png}, - asset_path("logo.png") - assert_match %r{/s/logo-[0-9a-f]+.png}, - asset_path("logo.png", :digest => true) - assert_match %r{/s/logo.png}, - asset_path("logo.png", :digest => false) - end - - test "asset_path with root relative assets" do - assert_equal "/images/logo", - asset_path("/images/logo") - assert_equal "/images/logo.gif", - asset_path("/images/logo.gif") - - assert_equal "/dir/audio", - asset_path("/dir/audio") - end - - test "asset_path with absolute urls" do - assert_equal "http://www.example.com/video/play", - asset_path("http://www.example.com/video/play") - assert_equal "http://www.example.com/video/play.mp4", - asset_path("http://www.example.com/video/play.mp4") - end - - test "with a simple asset host the url should default to protocol relative" do - @controller.config.default_asset_host_protocol = :relative - @controller.config.asset_host = "assets-%d.example.com" - assert_match %r{^//assets-\d.example.com/assets/logo-[0-9a-f]+.png}, - asset_path("logo.png") - end - - test "with a simple asset host the url can be changed to use the request protocol" do - @controller.config.asset_host = "assets-%d.example.com" - @controller.config.default_asset_host_protocol = :request - assert_match %r{http://assets-\d.example.com/assets/logo-[0-9a-f]+.png}, - asset_path("logo.png") - end - - test "With a proc asset host that returns no protocol the url should be protocol relative" do - @controller.config.default_asset_host_protocol = :relative - @controller.config.asset_host = Proc.new do |asset| - "assets-999.example.com" - end - assert_match %r{^//assets-999.example.com/assets/logo-[0-9a-f]+.png}, - asset_path("logo.png") - end - - test "with a proc asset host that returns a protocol the url use it" do - @controller.config.asset_host = Proc.new do |asset| - "http://assets-999.example.com" - end - assert_match %r{http://assets-999.example.com/assets/logo-[0-9a-f]+.png}, - asset_path("logo.png") - end - - test "stylesheets served with a controller in scope can access the request" do - config.asset_host = Proc.new do |asset, request| - assert_not_nil request - "http://assets-666.example.com" - end - assert_match %r{http://assets-666.example.com/assets/logo-[0-9a-f]+.png}, - asset_path("logo.png") - end - - test "stylesheets served without a controller in scope cannot access the request" do - @controller = nil - @config.asset_host = Proc.new do |asset, request| - fail "This should not have been called." - end - assert_raises ActionController::RoutingError do - asset_path("logo.png") - end - @config.asset_host = method :compute_host - assert_raises ActionController::RoutingError do - asset_path("logo.png") - end - end - - test "image_tag" do - assert_dom_equal '<img alt="Xml" src="/assets/xml.png" />', image_tag("xml.png") - end - - test "image_path" do - assert_match %r{/assets/logo-[0-9a-f]+.png}, - image_path("logo.png") - - assert_match %r{/assets/logo-[0-9a-f]+.png}, - path_to_image("logo.png") - end - - test "font_path" do - assert_match %r{/assets/font-[0-9a-f]+.ttf}, - font_path("font.ttf") - - assert_match %r{/assets/font-[0-9a-f]+.ttf}, - path_to_font("font.ttf") - end - - test "javascript_path" do - assert_match %r{/assets/application-[0-9a-f]+.js}, - javascript_path("application") - - assert_match %r{/assets/application-[0-9a-f]+.js}, - javascript_path("application.js") - - assert_match %r{/assets/application-[0-9a-f]+.js}, - path_to_javascript("application.js") - end - - test "stylesheet_path" do - assert_match %r{/assets/application-[0-9a-f]+.css}, - stylesheet_path("application") - - assert_match %r{/assets/application-[0-9a-f]+.css}, - stylesheet_path("application.css") - - assert_match %r{/assets/application-[0-9a-f]+.css}, - path_to_stylesheet("application.css") - end - - test "stylesheets served without a controller in do not use asset hosts when the default protocol is :request" do - @controller = nil - @config.asset_host = "assets-%d.example.com" - @config.default_asset_host_protocol = :request - @config.perform_caching = true - - assert_match %r{/assets/logo-[0-9a-f]+.png}, - asset_path("logo.png") - end - - test "asset path with relative url root" do - @controller.config.relative_url_root = "/collaboration/hieraki" - assert_equal "/collaboration/hieraki/images/logo.gif", - asset_path("/images/logo.gif") - end - - test "asset path with relative url root when controller isn't present but relative_url_root is" do - @controller = nil - @config.relative_url_root = "/collaboration/hieraki" - assert_equal "/collaboration/hieraki/images/logo.gif", - asset_path("/images/logo.gif") - end - - test "font path through asset_path" do - assert_match %r{/assets/font-[0-9a-f]+.ttf}, - asset_path('font.ttf') - - assert_match %r{/assets/dir/font-[0-9a-f]+.ttf}, - asset_path("dir/font.ttf") - - assert_equal "http://www.example.com/fonts/font.ttf", - asset_path("http://www.example.com/fonts/font.ttf") - end - - test "javascript path through asset_path" do - assert_match %r{/assets/application-[0-9a-f]+.js}, - asset_path(:application, :ext => "js") - - assert_match %r{/assets/xmlhr-[0-9a-f]+.js}, - asset_path("xmlhr", :ext => "js") - assert_match %r{/assets/dir/xmlhr-[0-9a-f]+.js}, - asset_path("dir/xmlhr.js", :ext => "js") - - assert_equal "/dir/xmlhr.js", - asset_path("/dir/xmlhr", :ext => "js") - - assert_equal "http://www.example.com/js/xmlhr", - asset_path("http://www.example.com/js/xmlhr", :ext => "js") - assert_equal "http://www.example.com/js/xmlhr.js", - asset_path("http://www.example.com/js/xmlhr.js", :ext => "js") - end - - test "javascript include tag" do - assert_match %r{<script src="/assets/application-[0-9a-f]+.js" type="text/javascript"></script>}, - javascript_include_tag(:application) - assert_match %r{<script src="/assets/application-[0-9a-f]+.js" type="text/javascript"></script>}, - javascript_include_tag(:application, :digest => true) - assert_match %r{<script src="/assets/application.js" type="text/javascript"></script>}, - javascript_include_tag(:application, :digest => false) - - assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js" type="text/javascript"></script>}, - javascript_include_tag("xmlhr") - assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js" type="text/javascript"></script>}, - javascript_include_tag("xmlhr.js") - assert_equal '<script src="http://www.example.com/xmlhr" type="text/javascript"></script>', - javascript_include_tag("http://www.example.com/xmlhr") - - assert_match %r{<script src=\"/assets/xmlhr-[0-9a-f]+.js" type=\"text/javascript\"></script>\n<script src=\"/assets/extra-[0-9a-f]+.js" type=\"text/javascript\"></script>}, - javascript_include_tag("xmlhr", "extra") - - assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js\?body=1" type="text/javascript"></script>\n<script src="/assets/application-[0-9a-f]+.js\?body=1" type="text/javascript"></script>}, - javascript_include_tag(:application, :debug => true) - - assert_match %r{<script src="/assets/jquery.plugin.js" type="text/javascript"></script>}, - javascript_include_tag('jquery.plugin', :digest => false) - - @config.assets.compile = true - @config.assets.debug = true - assert_match %r{<script src="/javascripts/application.js" type="text/javascript"></script>}, - javascript_include_tag('/javascripts/application') - assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js\?body=1" type="text/javascript"></script>\n<script src="/assets/application-[0-9a-f]+.js\?body=1" type="text/javascript"></script>}, - javascript_include_tag(:application) - end - - test "stylesheet path through asset_path" do - assert_match %r{/assets/application-[0-9a-f]+.css}, asset_path(:application, :ext => "css") - - assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", :ext => "css") - assert_match %r{/assets/dir/style-[0-9a-f]+.css}, asset_path("dir/style.css", :ext => "css") - assert_equal "/dir/style.css", asset_path("/dir/style.css", :ext => "css") - - assert_equal "http://www.example.com/css/style", - asset_path("http://www.example.com/css/style", :ext => "css") - assert_equal "http://www.example.com/css/style.css", - asset_path("http://www.example.com/css/style.css", :ext => "css") - end - - test "stylesheet link tag" do - assert_match %r{<link href="/assets/application-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag(:application) - assert_match %r{<link href="/assets/application-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag(:application, :digest => true) - assert_match %r{<link href="/assets/application.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag(:application, :digest => false) - - assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag("style") - assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag("style.css") - - assert_equal '<link href="http://www.example.com/style.css" media="screen" rel="stylesheet" type="text/css" />', - stylesheet_link_tag("http://www.example.com/style.css") - assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="all" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag("style", :media => "all") - assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="print" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag("style", :media => "print") - - assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/extra-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag("style", "extra") - - assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag(:application, :debug => true) - - @config.assets.compile = true - @config.assets.debug = true - assert_match %r{<link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag('/stylesheets/application') - - assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag(:application) - - assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="print" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="print" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag(:application, :media => "print") - end - - test "alternate asset prefix" do - stubs(:asset_prefix).returns("/themes/test") - assert_match %r{/themes/test/style-[0-9a-f]+.css}, asset_path("style", :ext => "css") - end - - test "alternate asset environment" do - assets = Sprockets::Environment.new - assets.append_path(FIXTURES.join("sprockets/alternate/stylesheets")) - stubs(:asset_environment).returns(assets) - assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", :ext => "css") - end - - test "alternate hash based on environment" do - assets = Sprockets::Environment.new - assets.version = 'development' - assets.append_path(FIXTURES.join("sprockets/alternate/stylesheets")) - stubs(:asset_environment).returns(assets) - dev_path = asset_path("style", :ext => "css") - - assets.version = 'production' - prod_path = asset_path("style", :ext => "css") - - assert_not_equal prod_path, dev_path - end - - test "precedence of `config.digest = false` over manifest.yml asset digests" do - Rails.application.config.assets.digests = {'logo.png' => 'logo-d1g3st.png'} - @config.assets.digest = false - - assert_equal '/assets/logo.png', - asset_path("logo.png") - end -end diff --git a/actionpack/test/template/sprockets_helper_with_routes_test.rb b/actionpack/test/template/sprockets_helper_with_routes_test.rb deleted file mode 100644 index bcbd81a7dd..0000000000 --- a/actionpack/test/template/sprockets_helper_with_routes_test.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'abstract_unit' -require 'sprockets' -require 'sprockets/helpers/rails_helper' -require 'mocha' - -class SprocketsHelperWithRoutesTest < ActionView::TestCase - include Sprockets::Helpers::RailsHelper - - # Let's bring in some named routes to test namespace conflicts with potential *_paths. - # We have to do this after we bring in the Sprockets RailsHelper so if there are conflicts, - # they'll fail in the way we expect in a real live Rails app. - routes = ActionDispatch::Routing::RouteSet.new - routes.draw do - resources :assets - end - include routes.url_helpers - - def setup - super - @controller = BasicController.new - - @assets = Sprockets::Environment.new - @assets.append_path(FIXTURES.join("sprockets/app/javascripts")) - @assets.append_path(FIXTURES.join("sprockets/app/stylesheets")) - @assets.append_path(FIXTURES.join("sprockets/app/images")) - - application = Struct.new(:config, :assets).new(config, @assets) - Rails.stubs(:application).returns(application) - @config = config - @config.perform_caching = true - @config.assets.digest = true - @config.assets.compile = true - end - - test "namespace conflicts on a named route called asset_path" do - # Testing this for sanity - asset_path is now a named route! - assert_match asset_path('test_asset'), '/assets/test_asset' - - assert_match %r{/assets/logo-[0-9a-f]+.png}, - path_to_asset("logo.png") - assert_match %r{/assets/logo-[0-9a-f]+.png}, - path_to_asset("logo.png", :digest => true) - assert_match %r{/assets/logo.png}, - path_to_asset("logo.png", :digest => false) - end - - test "javascript_include_tag with a named_route named asset_path" do - assert_match %r{<script src="/assets/application-[0-9a-f]+.js" type="text/javascript"></script>}, - javascript_include_tag(:application) - end - - test "stylesheet_link_tag with a named_route named asset_path" do - assert_match %r{<link href="/assets/application-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />}, - stylesheet_link_tag(:application) - end - -end
\ No newline at end of file diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb index 37858c1ba2..f2ed2ec609 100644 --- a/actionpack/test/template/test_case_test.rb +++ b/actionpack/test/template/test_case_test.rb @@ -277,6 +277,12 @@ module ActionView end class RenderTemplateTest < ActionView::TestCase + test "supports specifying templates with a Regexp" do + controller.controller_path = "fun" + render(:template => "fun/games/hello_world") + assert_template %r{\Afun/games/hello_world\Z} + end + test "supports specifying partials" do controller.controller_path = "test" render(:template => "test/calling_partial_with_layout") diff --git a/actionpack/test/ts_isolated.rb b/actionpack/test/ts_isolated.rb index 7430de2299..ae2a0c95f6 100644 --- a/actionpack/test/ts_isolated.rb +++ b/actionpack/test/ts_isolated.rb @@ -3,7 +3,6 @@ $:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib') require 'minitest/autorun' require 'rbconfig' -require 'active_support/core_ext/kernel/reporting' require 'abstract_unit' class TestIsolated < ActiveSupport::TestCase |