diff options
author | Pratik Naik <pratiknaik@gmail.com> | 2009-03-10 00:33:32 +0000 |
---|---|---|
committer | Pratik Naik <pratiknaik@gmail.com> | 2009-03-10 00:33:32 +0000 |
commit | 1ab84247ca4b80afbd82afe7539b3449636344c4 (patch) | |
tree | 9ca5e3bee3a07b68c9d900ff129b69bc740405c2 /actionpack | |
parent | b6fb79c531a0079274f7b459302e6290c9183f28 (diff) | |
parent | 4458edc882b229ea44602da20a6440a6f233f1c8 (diff) | |
download | rails-1ab84247ca4b80afbd82afe7539b3449636344c4.tar.gz rails-1ab84247ca4b80afbd82afe7539b3449636344c4.tar.bz2 rails-1ab84247ca4b80afbd82afe7539b3449636344c4.zip |
Merge commit 'mainstream/master'
Conflicts:
railties/guides/files/stylesheets/main.css
railties/guides/rails_guides/generator.rb
railties/guides/source/index.erb.textile
Diffstat (limited to 'actionpack')
49 files changed, 661 insertions, 219 deletions
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 546adeb61d..c4e4211c42 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,4 +1,10 @@ -*Edge* +*2.3.1 [RC2] (March 5, 2009)* + +* Fixed that redirection would just log the options, not the final url (which lead to "Redirected to #<Post:0x23150b8>") [DHH] + +* Added ability to pass in :public => true to fresh_when, stale?, and expires_in to make the request proxy cachable #2095 [Gregg Pollack] + +* Fixed that passing a custom form builder would be forwarded to nested fields_for calls #2023 [Eloy Duran/Nate Wiger] * Added partial scoping to TranslationHelper#translate, so if you call translate(".foo") from the people/index.html.erb template, you'll actually be calling I18n.translate("people.index.foo") [DHH] diff --git a/actionpack/Rakefile b/actionpack/Rakefile index c389e5a8d6..0d673c617d 100644 --- a/actionpack/Rakefile +++ b/actionpack/Rakefile @@ -80,7 +80,7 @@ spec = Gem::Specification.new do |s| s.has_rdoc = true s.requirements << 'none' - s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD) + s.add_dependency('activesupport', '= 2.3.1' + PKG_BUILD) s.add_dependency('rack', '>= 0.9.0') s.require_path = 'lib' diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 1eda6e3f04..0facf7066d 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -22,7 +22,7 @@ module ActionController #:nodoc: attr_reader :allowed_methods def initialize(*allowed_methods) - super("Only #{allowed_methods.to_sentence} requests are allowed.") + super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.") @allowed_methods = allowed_methods end @@ -908,12 +908,14 @@ module ActionController #:nodoc: end options = extra_options + elsif !options.is_a?(Hash) + extra_options[:partial] = options + options = extra_options end layout = pick_layout(options) response.layout = layout.path_without_format_and_extension if layout logger.info("Rendering template within #{layout.path_without_format_and_extension}") if logger && layout - layout = layout.path_without_format_and_extension if layout if content_type = options[:content_type] response.content_type = content_type.to_s @@ -1101,7 +1103,6 @@ module ActionController #:nodoc: end response.redirected_to = options - logger.info("Redirected to #{options}") if logger && logger.info? case options # The scheme name consist of a letter followed by any combination of @@ -1124,6 +1125,7 @@ module ActionController #:nodoc: def redirect_to_full_url(url, status) raise DoubleRenderError if performed? + logger.info("Redirected to #{url}") if logger && logger.info? response.redirect(url, interpret_status(status)) @performed_redirect = true end @@ -1133,6 +1135,11 @@ module ActionController #:nodoc: # request is considered stale and should be generated from scratch. Otherwise, # it's fresh and we don't need to generate anything and a reply of "304 Not Modified" is sent. # + # Parameters: + # * <tt>:etag</tt> + # * <tt>:last_modified</tt> + # * <tt>:public</tt> By default the Cache-Control header is private, set this to true if you want your application to be cachable by other devices (proxy caches). + # # Example: # # def show @@ -1153,20 +1160,34 @@ module ActionController #:nodoc: # Sets the etag, last_modified, or both on the response and renders a # "304 Not Modified" response if the request is already fresh. # + # Parameters: + # * <tt>:etag</tt> + # * <tt>:last_modified</tt> + # * <tt>:public</tt> By default the Cache-Control header is private, set this to true if you want your application to be cachable by other devices (proxy caches). + # # Example: # # def show # @article = Article.find(params[:id]) - # fresh_when(:etag => @article, :last_modified => @article.created_at.utc) + # fresh_when(:etag => @article, :last_modified => @article.created_at.utc, :public => true) # end # # This will render the show template if the request isn't sending a matching etag or # If-Modified-Since header and just a "304 Not Modified" response if there's a match. + # def fresh_when(options) - options.assert_valid_keys(:etag, :last_modified) + options.assert_valid_keys(:etag, :last_modified, :public) response.etag = options[:etag] if options[:etag] response.last_modified = options[:last_modified] if options[:last_modified] + + if options[:public] + cache_control = response.headers["Cache-Control"].split(",").map {|k| k.strip } + cache_control.delete("private") + cache_control.delete("no-cache") + cache_control << "public" + response.headers["Cache-Control"] = cache_control.join(', ') + end if request.fresh?(response) head :not_modified @@ -1178,15 +1199,26 @@ module ActionController #:nodoc: # # Examples: # expires_in 20.minutes - # expires_in 3.hours, :private => false - # expires in 3.hours, 'max-stale' => 5.hours, :private => nil, :public => true + # expires_in 3.hours, :public => 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. def expires_in(seconds, options = {}) #:doc: - cache_options = { 'max-age' => seconds, 'private' => true }.symbolize_keys.merge!(options.symbolize_keys) - cache_options.delete_if { |k,v| v.nil? or v == false } - cache_control = cache_options.map{ |k,v| v == true ? k.to_s : "#{k.to_s}=#{v.to_s}"} + cache_control = response.headers["Cache-Control"].split(",").map {|k| k.strip } + + cache_control << "max-age=#{seconds}" + cache_control.delete("no-cache") + if options[:public] + cache_control.delete("private") + cache_control << "public" + else + cache_control << "private" + end + + # This allows for additional headers to be passed through like 'max-stale' => 5.hours + cache_control += options.symbolize_keys.reject{|k,v| k == :public || k == :private }.map{ |k,v| v == true ? k.to_s : "#{k.to_s}=#{v.to_s}"} + response.headers["Cache-Control"] = cache_control.join(', ') end @@ -1298,7 +1330,7 @@ module ActionController #:nodoc: rescue ActionView::MissingTemplate => e # Was the implicit template missing, or was it another template? if e.path == default_template_name - raise UnknownAction, "No action responded to #{action_name}. Actions: #{action_methods.sort.to_sentence}", caller + raise UnknownAction, "No action responded to #{action_name}. Actions: #{action_methods.sort.to_sentence(:locale => :en)}", caller else raise e end diff --git a/actionpack/lib/action_controller/dispatcher.rb b/actionpack/lib/action_controller/dispatcher.rb index ec40b5c4e6..07931e4a4a 100644 --- a/actionpack/lib/action_controller/dispatcher.rb +++ b/actionpack/lib/action_controller/dispatcher.rb @@ -13,7 +13,6 @@ module ActionController end if defined?(ActiveRecord) - after_dispatch :checkin_connections to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers } end @@ -115,11 +114,5 @@ module ActionController def flush_logger Base.logger.flush end - - def checkin_connections - # Don't return connection (and peform implicit rollback) if this request is a part of integration test - return if @env.key?("rack.test") - ActiveRecord::Base.clear_active_connections! - end end end diff --git a/actionpack/lib/action_controller/layout.rb b/actionpack/lib/action_controller/layout.rb index a0db7acf72..6ec0c1b304 100644 --- a/actionpack/lib/action_controller/layout.rb +++ b/actionpack/lib/action_controller/layout.rb @@ -198,7 +198,7 @@ module ActionController #:nodoc: # is called and the return value is used. Likewise if the layout was specified as an inline method (through a proc or method # object). If the layout was defined without a directory, layouts is assumed. So <tt>layout "weblog/standard"</tt> will return # weblog/standard, but <tt>layout "standard"</tt> will return layouts/standard. - def active_layout(passed_layout = nil) + def active_layout(passed_layout = nil, options = {}) layout = passed_layout || default_layout return layout if layout.respond_to?(:render) @@ -207,21 +207,23 @@ module ActionController #:nodoc: when Proc then layout.call(self) else layout end - - find_layout(active_layout, @template.template_format) if active_layout + + find_layout(active_layout, default_template_format, options[:html_fallback]) if active_layout end private def default_layout #:nodoc: - layout = self.class.read_inheritable_attribute(:layout) unless default_template_format == :js + layout = self.class.read_inheritable_attribute(:layout) return layout unless self.class.read_inheritable_attribute(:auto_layout) find_layout(layout, default_template_format) rescue ActionView::MissingTemplate nil end - def find_layout(layout, *formats) #:nodoc: - view_paths.find_template(layout.to_s =~ /layouts\// ? layout : "layouts/#{layout}", *formats) + def find_layout(layout, format, html_fallback=false) #:nodoc: + view_paths.find_template(layout.to_s =~ /layouts\// ? layout : "layouts/#{layout}", format, html_fallback) + rescue ActionView::MissingTemplate + raise if Mime::Type.lookup_by_extension(format.to_s).html? end def pick_layout(options) @@ -232,7 +234,7 @@ module ActionController #:nodoc: when NilClass, TrueClass active_layout if action_has_layout? && candidate_for_layout?(:template => default_template_name) else - active_layout(layout) + active_layout(layout, :html_fallback => true) end else active_layout if action_has_layout? && candidate_for_layout?(options) @@ -258,7 +260,12 @@ module ActionController #:nodoc: template = options[:template] || default_template(options[:action]) if options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing, :update).compact.empty? begin - !self.view_paths.find_template(template, default_template_format).exempt_from_layout? + template_object = self.view_paths.find_template(template, default_template_format) + # this restores the behavior from 2.2.2, where response.template.template_format was reset + # to :html for :js requests with a matching html template. + # see v2.2.2, ActionView::Base, lines 328-330 + @real_format = :html if response.template.template_format == :js && template_object.format == "html" + !template_object.exempt_from_layout? rescue ActionView::MissingTemplate true end @@ -268,7 +275,7 @@ module ActionController #:nodoc: end def default_template_format - response.template.template_format + @real_format || response.template.template_format end end end diff --git a/actionpack/lib/action_controller/request.rb b/actionpack/lib/action_controller/request.rb index 0e95cfc147..2cabab9ec8 100755 --- a/actionpack/lib/action_controller/request.rb +++ b/actionpack/lib/action_controller/request.rb @@ -32,7 +32,7 @@ module ActionController # <tt>:get</tt>. If the request \method is not listed in the HTTP_METHODS # constant above, an UnknownHttpMethod exception is raised. def request_method - @request_method ||= HTTP_METHOD_LOOKUP[super] || raise(UnknownHttpMethod, "#{super}, accepted HTTP methods are #{HTTP_METHODS.to_sentence}") + @request_method ||= HTTP_METHOD_LOOKUP[super] || raise(UnknownHttpMethod, "#{super}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") end # Returns the HTTP request \method used for action processing as a diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb index 3af21967df..0a89c4b3d5 100644 --- a/actionpack/lib/action_controller/resources.rb +++ b/actionpack/lib/action_controller/resources.rb @@ -91,7 +91,7 @@ module ActionController end def shallow_path_prefix - @shallow_path_prefix ||= "#{path_prefix unless @options[:shallow]}" + @shallow_path_prefix ||= @options[:shallow] ? @options[:namespace].try(:sub, /\/$/, '') : path_prefix end def member_path @@ -103,7 +103,7 @@ module ActionController end def shallow_name_prefix - @shallow_name_prefix ||= "#{name_prefix unless @options[:shallow]}" + @shallow_name_prefix ||= @options[:shallow] ? @options[:namespace].try(:gsub, /\//, '_') : name_prefix end def nesting_name_prefix @@ -670,7 +670,12 @@ module ActionController when "show", "edit"; default_options.merge(add_conditions_for(resource.conditions, method || :get)).merge(resource.requirements(require_id)) when "update"; default_options.merge(add_conditions_for(resource.conditions, method || :put)).merge(resource.requirements(require_id)) when "destroy"; default_options.merge(add_conditions_for(resource.conditions, method || :delete)).merge(resource.requirements(require_id)) - else default_options.merge(add_conditions_for(resource.conditions, method)).merge(resource.requirements) + else + if method.nil? || resource.member_methods.nil? || resource.member_methods[method.to_sym].nil? + default_options.merge(add_conditions_for(resource.conditions, method)).merge(resource.requirements) + else + resource.member_methods[method.to_sym].include?(action) ? default_options.merge(add_conditions_for(resource.conditions, method)).merge(resource.requirements(require_id)) : default_options.merge(add_conditions_for(resource.conditions, method)).merge(resource.requirements) + end end end end diff --git a/actionpack/lib/action_controller/routing.rb b/actionpack/lib/action_controller/routing.rb index a2141a77dc..c0eb61340b 100644 --- a/actionpack/lib/action_controller/routing.rb +++ b/actionpack/lib/action_controller/routing.rb @@ -267,7 +267,7 @@ module ActionController module Routing SEPARATORS = %w( / . ? ) - HTTP_METHODS = [:get, :head, :post, :put, :delete] + HTTP_METHODS = [:get, :head, :post, :put, :delete, :options] ALLOWED_REQUIREMENTS_FOR_OPTIMISATION = [:controller, :action].to_set diff --git a/actionpack/lib/action_controller/routing/builder.rb b/actionpack/lib/action_controller/routing/builder.rb index 44d759444a..d9590c88b8 100644 --- a/actionpack/lib/action_controller/routing/builder.rb +++ b/actionpack/lib/action_controller/routing/builder.rb @@ -159,7 +159,8 @@ module ActionController path = "/#{path}" unless path[0] == ?/ path = "#{path}/" unless path[-1] == ?/ - path = "/#{options[:path_prefix].to_s.gsub(/^\//,'')}#{path}" if options[:path_prefix] + prefix = options[:path_prefix].to_s.gsub(/^\//,'') + path = "/#{prefix}#{path}" unless prefix.blank? segments = segments_for_route_path(path) defaults, requirements, conditions = divide_route_options(segments, options) diff --git a/actionpack/lib/action_controller/routing/recognition_optimisation.rb b/actionpack/lib/action_controller/routing/recognition_optimisation.rb index ebc553512f..9bfebff0c0 100644 --- a/actionpack/lib/action_controller/routing/recognition_optimisation.rb +++ b/actionpack/lib/action_controller/routing/recognition_optimisation.rb @@ -98,7 +98,6 @@ module ActionController if Array === item i += 1 start = (i == 1) - final = (i == list.size) tag, sub = item if tag == :dynamic body += padding + "#{start ? 'if' : 'elsif'} true\n" diff --git a/actionpack/lib/action_controller/routing/segments.rb b/actionpack/lib/action_controller/routing/segments.rb index 129e87c139..4f936d51d2 100644 --- a/actionpack/lib/action_controller/routing/segments.rb +++ b/actionpack/lib/action_controller/routing/segments.rb @@ -3,7 +3,11 @@ module ActionController class Segment #:nodoc: RESERVED_PCHAR = ':@&=+$,;' SAFE_PCHAR = "#{URI::REGEXP::PATTERN::UNRESERVED}#{RESERVED_PCHAR}" - UNSAFE_PCHAR = Regexp.new("[^#{SAFE_PCHAR}]", false, 'N').freeze + if RUBY_VERSION >= '1.9' + UNSAFE_PCHAR = Regexp.new("[^#{SAFE_PCHAR}]", false).freeze + else + UNSAFE_PCHAR = Regexp.new("[^#{SAFE_PCHAR}]", false, 'N').freeze + end # TODO: Convert :is_optional accessor to read only attr_accessor :is_optional @@ -314,13 +318,17 @@ module ActionController end def regexp_chunk - '(\.[^/?\.]+)?' + '/|(\.[^/?\.]+)?' end def to_s '(.:format)?' end - + + def extract_value + "#{local_name} = options[:#{key}] && options[:#{key}].to_s.downcase" + end + #the value should not include the period (.) def match_extraction(next_capture) %[ diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb index 376bb87409..e2c49c284f 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb +++ b/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb @@ -556,7 +556,7 @@ module HTML end # Attribute value. - next if statement.sub!(/^\[\s*([[:alpha:]][\w\-]*)\s*((?:[~|^$*])?=)?\s*('[^']*'|"[^*]"|[^\]]*)\s*\]/) do |match| + next if statement.sub!(/^\[\s*([[:alpha:]][\w\-:]*)\s*((?:[~|^$*])?=)?\s*('[^']*'|"[^*]"|[^\]]*)\s*\]/) do |match| name, equality, value = $1, $2, $3 if value == "?" value = values.shift diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb index f20e44a7d5..f03a2a7605 100644 --- a/actionpack/lib/action_pack/version.rb +++ b/actionpack/lib/action_pack/version.rb @@ -2,7 +2,7 @@ module ActionPack #:nodoc: module VERSION #:nodoc: MAJOR = 2 MINOR = 3 - TINY = 0 + TINY = 1 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 65b2062337..fe6053e574 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -183,12 +183,12 @@ module ActionView #:nodoc: cattr_accessor :debug_rjs # Specify whether templates should be cached. Otherwise the file we be read everytime it is accessed. - # Automaticaly reloading templates are not thread safe and should only be used in development mode. - @@cache_template_loading = false + # Automatically reloading templates are not thread safe and should only be used in development mode. + @@cache_template_loading = nil cattr_accessor :cache_template_loading def self.cache_template_loading? - ActionController::Base.allow_concurrency || cache_template_loading + ActionController::Base.allow_concurrency || (cache_template_loading.nil? ? !ActiveSupport::Dependencies.load? : cache_template_loading) end attr_internal :request diff --git a/actionpack/lib/action_view/helpers/active_record_helper.rb b/actionpack/lib/action_view/helpers/active_record_helper.rb index 8b56d241ae..541899ea6a 100644 --- a/actionpack/lib/action_view/helpers/active_record_helper.rb +++ b/actionpack/lib/action_view/helpers/active_record_helper.rb @@ -121,7 +121,7 @@ module ActionView if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) && (errors = obj.errors.on(method)) content_tag("div", - "#{options[:prepend_text]}#{errors.is_a?(Array) ? errors.first : errors}#{options[:append_text]}", + "#{options[:prepend_text]}#{ERB::Util.html_escape(errors.is_a?(Array) ? errors.first : errors)}#{options[:append_text]}", :class => options[:css_class] ) else @@ -198,7 +198,7 @@ module ActionView locale.t :header, :count => count, :model => object_name end message = options.include?(:message) ? options[:message] : locale.t(:body) - error_messages = objects.sum {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } }.join + error_messages = objects.sum {|object| object.errors.full_messages.map {|msg| content_tag(:li, ERB::Util.html_escape(msg)) } }.join contents = '' contents << content_tag(options[:header_tag] || :h2, header_message) unless header_message.blank? diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index 4fef2b443e..a589bcba2a 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -5,17 +5,24 @@ require 'action_view/helpers/form_tag_helper' module ActionView module Helpers - # Form helpers are designed to make working with models much easier compared to using just standard HTML - # elements by providing a set of methods for creating forms based on your models. This helper generates the HTML - # for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form - # is submitted (i.e., when the user hits the submit button or <tt>form.submit</tt> is called via JavaScript), the form inputs will be bundled into the <tt>params</tt> object and passed back to the controller. + # Form helpers are designed to make working with models much easier + # compared to using just standard HTML elements by providing a set of + # methods for creating forms based on your models. This helper generates + # the HTML for forms, providing a method for each sort of input + # (e.g., text, password, select, and so on). When the form is submitted + # (i.e., when the user hits the submit button or <tt>form.submit</tt> is + # called via JavaScript), the form inputs will be bundled into the + # <tt>params</tt> object and passed back to the controller. # - # There are two types of form helpers: those that specifically work with model attributes and those that don't. - # This helper deals with those that work with model attributes; to see an example of form helpers that don't work - # with model attributes, check the ActionView::Helpers::FormTagHelper documentation. + # There are two types of form helpers: those that specifically work with + # model attributes and those that don't. This helper deals with those that + # work with model attributes; to see an example of form helpers that don't + # work with model attributes, check the ActionView::Helpers::FormTagHelper + # documentation. # - # The core method of this helper, form_for, gives you the ability to create a form for a model instance; - # for example, let's say that you have a model <tt>Person</tt> and want to create a new instance of it: + # The core method of this helper, form_for, gives you the ability to create + # a form for a model instance; for example, let's say that you have a model + # <tt>Person</tt> and want to create a new instance of it: # # # Note: a @person variable will have been created in the controller. # # For example: @person = Person.new @@ -40,17 +47,22 @@ module ActionView # <%= submit_tag 'Create' %> # <% end %> # - # This example will render the <tt>people/_form</tt> partial, setting a local variable called <tt>form</tt> which references the yielded FormBuilder. - # - # The <tt>params</tt> object created when this form is submitted would look like: + # This example will render the <tt>people/_form</tt> partial, setting a + # local variable called <tt>form</tt> which references the yielded + # FormBuilder. The <tt>params</tt> object created when this form is + # submitted would look like: # # {"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}} # - # The params hash has a nested <tt>person</tt> value, which can therefore be accessed with <tt>params[:person]</tt> in the controller. - # If were editing/updating an instance (e.g., <tt>Person.find(1)</tt> rather than <tt>Person.new</tt> in the controller), the objects - # attribute values are filled into the form (e.g., the <tt>person_first_name</tt> field would have that person's first name in it). + # The params hash has a nested <tt>person</tt> value, which can therefore + # be accessed with <tt>params[:person]</tt> in the controller. If were + # editing/updating an instance (e.g., <tt>Person.find(1)</tt> rather than + # <tt>Person.new</tt> in the controller), the objects attribute values are + # filled into the form (e.g., the <tt>person_first_name</tt> field would + # have that person's first name in it). # - # If the object name contains square brackets the id for the object will be inserted. For example: + # If the object name contains square brackets the id for the object will be + # inserted. For example: # # <%= text_field "person[]", "name" %> # @@ -58,8 +70,10 @@ module ActionView # # <input type="text" id="person_<%= @person.id %>_name" name="person[<%= @person.id %>][name]" value="<%= @person.name %>" /> # - # If the helper is being used to generate a repetitive sequence of similar form elements, for example in a partial - # used by <tt>render_collection_of_partials</tt>, the <tt>index</tt> option may come in handy. Example: + # If the helper is being used to generate a repetitive sequence of similar + # form elements, for example in a partial used by + # <tt>render_collection_of_partials</tt>, the <tt>index</tt> option may + # come in handy. Example: # # <%= text_field "person", "name", "index" => 1 %> # @@ -67,14 +81,17 @@ module ActionView # # <input type="text" id="person_1_name" name="person[1][name]" value="<%= @person.name %>" /> # - # An <tt>index</tt> option may also be passed to <tt>form_for</tt> and <tt>fields_for</tt>. This automatically applies - # the <tt>index</tt> to all the nested fields. + # An <tt>index</tt> option may also be passed to <tt>form_for</tt> and + # <tt>fields_for</tt>. This automatically applies the <tt>index</tt> to + # all the nested fields. # - # There are also methods for helping to build form tags in link:classes/ActionView/Helpers/FormOptionsHelper.html, - # link:classes/ActionView/Helpers/DateHelper.html, and link:classes/ActionView/Helpers/ActiveRecordHelper.html + # There are also methods for helping to build form tags in + # link:classes/ActionView/Helpers/FormOptionsHelper.html, + # link:classes/ActionView/Helpers/DateHelper.html, and + # link:classes/ActionView/Helpers/ActiveRecordHelper.html module FormHelper - # 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 and a scope around a specific model object that is used + # as a base for questioning about values for the fields. # # Rails provides succinct resource-oriented form generation with +form_for+ # like this: @@ -86,13 +103,15 @@ module ActionView # <%= f.text_field :author %><br /> # <% 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. + # 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 generic way to call +form_for+ yields a form builder around a + # model: # # <% form_for :person, :url => { :action => "update" } do |f| %> # <%= f.error_messages %> @@ -103,8 +122,8 @@ module ActionView # <% end %> # # There, the first argument is a symbol or string with the name of the - # object the form is about, and also the name of the instance variable the - # object is stored in. + # object the form is about, and also the name of the instance variable + # the object is stored in. # # The form builder acts as a regular form helper that somehow carries the # model. Thus, the idea is that @@ -137,17 +156,18 @@ module ActionView # In any of its variants, 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. + # * <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. # * <tt>:html</tt> - Optional HTML attributes for the form tag. # - # Worth noting is that the +form_for+ tag is called in a ERb evaluation block, - # not an ERb output block. So that's <tt><% %></tt>, not <tt><%= %></tt>. + # Worth noting is that the +form_for+ tag is called in a ERb evaluation + # block, not an ERb output block. So that's <tt><% %></tt>, not + # <tt><%= %></tt>. # # Also note that +form_for+ doesn't create an exclusive scope. It's still - # possible to use both the stand-alone FormHelper methods and methods from - # FormTagHelper. For example: + # possible to use both the stand-alone FormHelper methods and methods + # from FormTagHelper. For example: # # <% form_for :person, @person, :url => { :action => "update" } do |f| %> # First name: <%= f.text_field :first_name %> @@ -156,16 +176,16 @@ module ActionView # Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %> # <% end %> # - # 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. + # 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. # # === Resource-oriented style # - # 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. + # 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. # # For example, if <tt>@post</tt> is an existing record you want to edit # @@ -205,8 +225,10 @@ module ActionView # # === Customized form builders # - # You can also build forms using a customized FormBuilder class. Subclass FormBuilder and override or define some more helpers, - # then use your custom builder. For example, let's say you made a helper to automatically add labels to form inputs. + # You can also build forms using a customized FormBuilder class. Subclass + # FormBuilder and override or define some more helpers, then use your + # custom builder. For example, let's say you made a helper to + # automatically add labels to form inputs. # # <% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %> # <%= f.text_field :first_name %> @@ -219,16 +241,23 @@ module ActionView # # <%= render :partial => f %> # - # The rendered template is <tt>people/_labelling_form</tt> and the local variable referencing the form builder is called <tt>labelling_form</tt>. + # The rendered template is <tt>people/_labelling_form</tt> and the local + # variable referencing the form builder is called + # <tt>labelling_form</tt>. + # + # The custom FormBuilder class is automatically merged with the options + # of a nested fields_for call, unless it's explicitely set. # - # In many cases you will want to wrap the above in another helper, so you could do something like the following: + # In many cases you will want to wrap the above in another helper, so you + # could do something like the following: # # def labelled_form_for(record_or_name_or_array, *args, &proc) # options = args.extract_options! # form_for(record_or_name_or_array, *(args << options.merge(:builder => LabellingFormBuilder)), &proc) # end # - # If you don't need to attach a form to a model instance, then check out FormTagHelper#form_tag. + # If you don't need to attach a form to a model instance, then check out + # FormTagHelper#form_tag. def form_for(record_or_name_or_array, *args, &proc) raise ArgumentError, "Missing block" unless block_given? @@ -910,6 +939,11 @@ module ActionView index = "" end + if options[:builder] + args << {} unless args.last.is_a?(Hash) + args.last[:builder] ||= options[:builder] + end + case record_or_name_or_array when String, Symbol if nested_attributes_association?(record_or_name_or_array) diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 4646bc118b..6d39a53adc 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -360,8 +360,8 @@ module ActionView end if confirm = options.delete("confirm") - options["onclick"] ||= '' - options["onclick"] << "return #{confirm_javascript_function(confirm)};" + options["onclick"] ||= 'return true;' + options["onclick"] = "if (!#{confirm_javascript_function(confirm)}) return false; #{options['onclick']}" end tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys) diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb index e622f97b9e..539f43c6e3 100644 --- a/actionpack/lib/action_view/helpers/number_helper.rb +++ b/actionpack/lib/action_view/helpers/number_helper.rb @@ -15,6 +15,7 @@ module ActionView # * <tt>:country_code</tt> - Sets the country code for the phone number. # # ==== Examples + # number_to_phone(5551234) # => 555-1234 # number_to_phone(1235551234) # => 123-555-1234 # number_to_phone(1235551234, :area_code => true) # => (123) 555-1234 # number_to_phone(1235551234, :delimiter => " ") # => 123 555 1234 @@ -37,7 +38,8 @@ module ActionView str << if area_code number.gsub!(/([0-9]{1,3})([0-9]{3})([0-9]{4}$)/,"(\\1) \\2#{delimiter}\\3") else - number.gsub!(/([0-9]{1,3})([0-9]{3})([0-9]{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3") + number.gsub!(/([0-9]{0,3})([0-9]{3})([0-9]{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3") + number.starts_with?('-') ? number.slice!(1..-1) : number end str << " x #{extension}" unless extension.blank? str diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb index 18a209dcea..91ef72e54b 100644 --- a/actionpack/lib/action_view/helpers/prototype_helper.rb +++ b/actionpack/lib/action_view/helpers/prototype_helper.rb @@ -107,7 +107,7 @@ module ActionView # on the page in an Ajax response. module PrototypeHelper unless const_defined? :CALLBACKS - CALLBACKS = Set.new([ :uninitialized, :loading, :loaded, + CALLBACKS = Set.new([ :create, :uninitialized, :loading, :loaded, :interactive, :complete, :failure, :success ] + (100..599).to_a) AJAX_OPTIONS = Set.new([ :before, :after, :condition, :url, diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb index 41f9f486e5..37d96b2f82 100644 --- a/actionpack/lib/action_view/paths.rb +++ b/actionpack/lib/action_view/paths.rb @@ -40,7 +40,7 @@ module ActionView #:nodoc: each(&:load!) end - def find_template(original_template_path, format = nil) + def find_template(original_template_path, format = nil, html_fallback = true) return original_template_path if original_template_path.respond_to?(:render) template_path = original_template_path.sub(/^\//, '') @@ -54,9 +54,9 @@ module ActionView #:nodoc: elsif template = load_path[template_path] return template # Try to find html version if the format is javascript - elsif format == :js && template = load_path["#{template_path}.#{I18n.locale}.html"] + elsif format == :js && html_fallback && template = load_path["#{template_path}.#{I18n.locale}.html"] return template - elsif format == :js && template = load_path["#{template_path}.html"] + elsif format == :js && html_fallback && template = load_path["#{template_path}.html"] return template end end diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index ea838b9b02..0dd3a7e619 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -103,12 +103,12 @@ module ActionView #:nodoc: @@exempt_from_layout.merge(regexps) end - attr_accessor :filename, :load_path, :base_path + attr_accessor :template_path, :filename, :load_path, :base_path attr_accessor :locale, :name, :format, :extension delegate :to_s, :to => :path def initialize(template_path, load_path) - template_path = template_path.dup + @template_path = template_path.dup @load_path, @filename = load_path, File.join(load_path, template_path) @base_path, @name, @locale, @format, @extension = split(template_path) @base_path.to_s.gsub!(/\/$/, '') # Push to split method @@ -119,13 +119,20 @@ module ActionView #:nodoc: def accessible_paths paths = [] - paths << path - paths << path_without_extension - if multipart? - formats = format.split(".") - paths << "#{path_without_format_and_extension}.#{formats.first}" - paths << "#{path_without_format_and_extension}.#{formats.second}" + + if valid_extension?(extension) + paths << path + paths << path_without_extension + if multipart? + formats = format.split(".") + paths << "#{path_without_format_and_extension}.#{formats.first}" + paths << "#{path_without_format_and_extension}.#{formats.second}" + end + else + # template without explicit template handler should only be reachable through its exact path + paths << template_path end + paths end diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb index 6a75e6050d..7998f9c22f 100644 --- a/actionpack/test/activerecord/active_record_store_test.rb +++ b/actionpack/test/activerecord/active_record_store_test.rb @@ -21,6 +21,11 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest render :text => "foo: #{session[:foo].inspect}" end + def call_reset_session + reset_session + head :ok + end + def rescue_action(e) raise end end @@ -61,6 +66,22 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest end end + def test_setting_session_value_after_session_reset + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] + + get '/call_reset_session' + assert_response :success + assert_not_equal [], headers['Set-Cookie'] + + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body + end + end + def test_prevents_session_fixation with_test_route_set do get '/set_session_value' diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index 99c57c0c91..298c7e4db3 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -76,7 +76,7 @@ class AssertSelectTest < ActionController::TestCase end def assert_failure(message, &block) - e = assert_raises(Assertion, &block) + e = assert_raise(Assertion, &block) assert_match(message, e.message) if Regexp === message assert_equal(message, e.message) if String === message end @@ -95,24 +95,24 @@ class AssertSelectTest < ActionController::TestCase def test_equality_true_false render_html %Q{<div id="1"></div><div id="2"></div>} assert_nothing_raised { assert_select "div" } - assert_raises(Assertion) { assert_select "p" } + assert_raise(Assertion) { assert_select "p" } assert_nothing_raised { assert_select "div", true } - assert_raises(Assertion) { assert_select "p", true } - assert_raises(Assertion) { assert_select "div", false } + assert_raise(Assertion) { assert_select "p", true } + assert_raise(Assertion) { assert_select "div", false } assert_nothing_raised { assert_select "p", false } end def test_equality_string_and_regexp render_html %Q{<div id="1">foo</div><div id="2">foo</div>} assert_nothing_raised { assert_select "div", "foo" } - assert_raises(Assertion) { assert_select "div", "bar" } + assert_raise(Assertion) { assert_select "div", "bar" } assert_nothing_raised { assert_select "div", :text=>"foo" } - assert_raises(Assertion) { assert_select "div", :text=>"bar" } + assert_raise(Assertion) { assert_select "div", :text=>"bar" } assert_nothing_raised { assert_select "div", /(foo|bar)/ } - assert_raises(Assertion) { assert_select "div", /foobar/ } + assert_raise(Assertion) { assert_select "div", /foobar/ } assert_nothing_raised { assert_select "div", :text=>/(foo|bar)/ } - assert_raises(Assertion) { assert_select "div", :text=>/foobar/ } - assert_raises(Assertion) { assert_select "p", :text=>/foobar/ } + assert_raise(Assertion) { assert_select "div", :text=>/foobar/ } + assert_raise(Assertion) { assert_select "p", :text=>/foobar/ } end def test_equality_of_html @@ -120,17 +120,17 @@ class AssertSelectTest < ActionController::TestCase text = "\"This is not a big problem,\" he said." html = "<em>\"This is <strong>not</strong> a big problem,\"</em> he said." assert_nothing_raised { assert_select "p", text } - assert_raises(Assertion) { assert_select "p", html } + assert_raise(Assertion) { assert_select "p", html } assert_nothing_raised { assert_select "p", :html=>html } - assert_raises(Assertion) { assert_select "p", :html=>text } + assert_raise(Assertion) { assert_select "p", :html=>text } # No stripping for pre. render_html %Q{<pre>\n<em>"This is <strong>not</strong> a big problem,"</em> he said.\n</pre>} text = "\n\"This is not a big problem,\" he said.\n" html = "\n<em>\"This is <strong>not</strong> a big problem,\"</em> he said.\n" assert_nothing_raised { assert_select "pre", text } - assert_raises(Assertion) { assert_select "pre", html } + assert_raise(Assertion) { assert_select "pre", html } assert_nothing_raised { assert_select "pre", :html=>html } - assert_raises(Assertion) { assert_select "pre", :html=>text } + assert_raise(Assertion) { assert_select "pre", :html=>text } end def test_counts @@ -210,12 +210,12 @@ class AssertSelectTest < ActionController::TestCase assert_nothing_raised { assert_select "div", "bar" } assert_nothing_raised { assert_select "div", /\w*/ } assert_nothing_raised { assert_select "div", /\w*/, :count=>2 } - assert_raises(Assertion) { assert_select "div", :text=>"foo", :count=>2 } + assert_raise(Assertion) { assert_select "div", :text=>"foo", :count=>2 } assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" } assert_nothing_raised { assert_select "div", :html=>"<span>bar</span>" } assert_nothing_raised { assert_select "div", :html=>/\w*/ } assert_nothing_raised { assert_select "div", :html=>/\w*/, :count=>2 } - assert_raises(Assertion) { assert_select "div", :html=>"<span>foo</span>", :count=>2 } + assert_raise(Assertion) { assert_select "div", :html=>"<span>foo</span>", :count=>2 } end end @@ -253,7 +253,12 @@ class AssertSelectTest < ActionController::TestCase page.insert_html :top, "test1", "<div id=\"1\">foo</div>" page.insert_html :bottom, "test2", "<div id=\"2\">foo</div>" end - assert_raises(Assertion) {assert_select_rjs :insert, :top, "test2"} + assert_raise(Assertion) {assert_select_rjs :insert, :top, "test2"} + end + + def test_elect_with_xml_namespace_attributes + render_html %Q{<link xlink:href="http://nowhere.com"></link>} + assert_nothing_raised { assert_select "link[xlink:href=http://nowhere.com]" } end # @@ -331,7 +336,7 @@ class AssertSelectTest < ActionController::TestCase # Test that we fail if there is nothing to pick. def test_assert_select_rjs_fails_if_nothing_to_pick render_rjs { } - assert_raises(Assertion) { assert_select_rjs } + assert_raise(Assertion) { assert_select_rjs } end def test_assert_select_rjs_with_unicode @@ -346,10 +351,10 @@ class AssertSelectTest < ActionController::TestCase if str.respond_to?(:force_encoding) str.force_encoding(Encoding::UTF_8) assert_select str, /\343\203\201..\343\203\210/u - assert_raises(Assertion) { assert_select str, /\343\203\201.\343\203\210/u } + assert_raise(Assertion) { assert_select str, /\343\203\201.\343\203\210/u } else assert_select str, Regexp.new("\343\203\201..\343\203\210",0,'U') - assert_raises(Assertion) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') } + assert_raise(Assertion) { assert_select str, Regexp.new("\343\203\201.\343\203\210",0,'U') } end end end @@ -373,7 +378,7 @@ class AssertSelectTest < ActionController::TestCase assert_select "div", 1 assert_select "#3" end - assert_raises(Assertion) { assert_select_rjs "test4" } + assert_raise(Assertion) { assert_select_rjs "test4" } end def test_assert_select_rjs_for_replace @@ -391,7 +396,7 @@ class AssertSelectTest < ActionController::TestCase assert_select "div", 1 assert_select "#1" end - assert_raises(Assertion) { assert_select_rjs :replace, "test2" } + assert_raise(Assertion) { assert_select_rjs :replace, "test2" } # Replace HTML. assert_select_rjs :replace_html do assert_select "div", 1 @@ -401,7 +406,7 @@ class AssertSelectTest < ActionController::TestCase assert_select "div", 1 assert_select "#2" end - assert_raises(Assertion) { assert_select_rjs :replace_html, "test1" } + assert_raise(Assertion) { assert_select_rjs :replace_html, "test1" } end def test_assert_select_rjs_for_chained_replace @@ -419,7 +424,7 @@ class AssertSelectTest < ActionController::TestCase assert_select "div", 1 assert_select "#1" end - assert_raises(Assertion) { assert_select_rjs :chained_replace, "test2" } + assert_raise(Assertion) { assert_select_rjs :chained_replace, "test2" } # Replace HTML. assert_select_rjs :chained_replace_html do assert_select "div", 1 @@ -429,7 +434,7 @@ class AssertSelectTest < ActionController::TestCase assert_select "div", 1 assert_select "#2" end - assert_raises(Assertion) { assert_select_rjs :replace_html, "test1" } + assert_raise(Assertion) { assert_select_rjs :replace_html, "test1" } end # Simple remove @@ -575,7 +580,7 @@ class AssertSelectTest < ActionController::TestCase assert_select "div", 1 assert_select "#3" end - assert_raises(Assertion) { assert_select_rjs :insert_html, "test1" } + assert_raise(Assertion) { assert_select_rjs :insert_html, "test1" } end # Positioned insert. @@ -608,8 +613,8 @@ class AssertSelectTest < ActionController::TestCase end def test_assert_select_rjs_raise_errors - assert_raises(ArgumentError) { assert_select_rjs(:destroy) } - assert_raises(ArgumentError) { assert_select_rjs(:insert, :left) } + assert_raise(ArgumentError) { assert_select_rjs(:destroy) } + assert_raise(ArgumentError) { assert_select_rjs(:insert, :left) } end # Simple selection from a single result. @@ -701,7 +706,7 @@ EOF # def test_assert_select_email - assert_raises(Assertion) { assert_select_email {} } + assert_raise(Assertion) { assert_select_email {} } AssertSelectMailer.deliver_test "<div><p>foo</p><p>bar</p></div>" assert_select_email do assert_select "div:root" do diff --git a/actionpack/test/controller/fake_models.rb b/actionpack/test/controller/fake_models.rb index 7420579ed8..0b30c79b10 100644 --- a/actionpack/test/controller/fake_models.rb +++ b/actionpack/test/controller/fake_models.rb @@ -9,3 +9,11 @@ end class GoodCustomer < Customer end + +module Quiz + class Question < Struct.new(:name, :id) + def to_param + id.to_s + end + end +end diff --git a/actionpack/test/controller/html-scanner/document_test.rb b/actionpack/test/controller/html-scanner/document_test.rb index 1c3facb9e3..c68f04fa75 100644 --- a/actionpack/test/controller/html-scanner/document_test.rb +++ b/actionpack/test/controller/html-scanner/document_test.rb @@ -134,7 +134,7 @@ HTML end def test_invalid_document_raises_exception_when_strict - assert_raises RuntimeError do + assert_raise RuntimeError do doc = HTML::Document.new("<html> <table> <tr> diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index 28555ee3d1..1575674e18 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -79,6 +79,10 @@ end class DefaultLayoutController < LayoutTest end +class AbsolutePathLayoutController < LayoutTest + layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.rhtml') +end + class HasOwnLayoutController < LayoutTest layout 'item' end @@ -137,12 +141,18 @@ class LayoutSetInResponseTest < ActionController::TestCase ensure ActionController::Base.exempt_from_layout.delete(/\.rhtml$/) end - + def test_layout_is_picked_from_the_controller_instances_view_path @controller = PrependsViewPathController.new get :hello assert_equal 'layouts/alt', @response.layout end + + def test_absolute_pathed_layout + @controller = AbsolutePathLayoutController.new + get :hello + assert_equal "layout_test.rhtml hello.rhtml", @response.body.strip + end end class RenderWithTemplateOptionController < LayoutTest diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index dc59180a68..edd7162325 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -469,7 +469,7 @@ class MimeControllerTest < ActionController::TestCase assert_equal '<html><div id="html_missing">Hello future from Firefox!</div></html>', @response.body @request.accept = "text/iphone" - assert_raises(ActionView::MissingTemplate) { get :iphone_with_html_response_type_without_layout } + assert_raise(ActionView::MissingTemplate) { get :iphone_with_html_response_type_without_layout } end end diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index 27cedc91d2..91e21db854 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -212,7 +212,7 @@ class RedirectTest < ActionController::TestCase end def test_redirect_to_back_with_no_referer - assert_raises(ActionController::RedirectBackError) { + assert_raise(ActionController::RedirectBackError) { @request.env["HTTP_REFERER"] = nil get :redirect_to_back } @@ -239,7 +239,7 @@ class RedirectTest < ActionController::TestCase end def test_redirect_to_nil - assert_raises(ActionController::ActionControllerError) do + assert_raise(ActionController::ActionControllerError) do get :redirect_to_nil end end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index e131a735a9..af623395f0 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -36,6 +36,39 @@ class TestController < ActionController::Base render :action => 'hello_world' end end + + def conditional_hello_with_public_header + if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) + render :action => 'hello_world' + end + end + + def conditional_hello_with_public_header_and_expires_at + expires_in 1.minute + if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) + render :action => 'hello_world' + end + end + + def conditional_hello_with_expires_in + expires_in 1.minute + render :action => 'hello_world' + end + + def conditional_hello_with_expires_in_with_public + expires_in 1.minute, :public => true + render :action => 'hello_world' + end + + def conditional_hello_with_expires_in_with_public_with_more_keys + expires_in 1.minute, :public => true, 'max-stale' => 5.hours + render :action => 'hello_world' + end + + def conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax + expires_in 1.minute, :public => true, :private => nil, 'max-stale' => 5.hours + render :action => 'hello_world' + end def conditional_hello_with_bangs render :action => 'hello_world' @@ -280,6 +313,10 @@ class TestController < ActionController::Base def render_implicit_js_template_without_layout end + def render_html_explicit_template_and_layout + render :template => 'test/render_implicit_html_template_from_xhr_request', :layout => 'layouts/default_html' + end + def formatted_html_erb end @@ -645,6 +682,14 @@ class TestController < ActionController::Base render :partial => "hash_object", :object => {:first_name => "Sam"} end + def partial_with_nested_object + render :partial => "quiz/questions/question", :object => Quiz::Question.new("first") + end + + def partial_with_nested_object_shorthand + render Quiz::Question.new("first") + end + def partial_hash_collection render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ] end @@ -684,12 +729,15 @@ class TestController < ActionController::Base "render_with_explicit_string_template", "render_js_with_explicit_template", "render_js_with_explicit_action_template", - "delete_with_js", "update_page", "update_page_with_instance_variables", - "render_implicit_js_template_without_layout" + "delete_with_js", "update_page", "update_page_with_instance_variables" "layouts/standard" + when "render_implicit_js_template_without_layout" + "layouts/default_html" when "action_talk_to_layout", "layout_overriding_layout" "layouts/talk_from_action" + when "render_implicit_html_template_from_xhr_request" + (request.xhr? ? 'layouts/xhr' : 'layouts/standard') end end end @@ -783,6 +831,11 @@ class RenderTest < ActionController::TestCase assert_equal "<html>hello world, I'm here!</html>", @response.body end + def test_xhr_with_render_text_and_layout + xhr :get, :render_text_hello_world_with_layout + assert_equal "<html>hello world, I'm here!</html>", @response.body + end + def test_do_with_render_action_and_layout_false get :hello_world_with_layout_false assert_equal 'Hello world!', @response.body @@ -884,11 +937,11 @@ class RenderTest < ActionController::TestCase end def test_attempt_to_access_object_method - assert_raises(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } + assert_raise(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } end def test_private_methods - assert_raises(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout } + assert_raise(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout } end def test_access_to_request_in_view @@ -1018,8 +1071,13 @@ class RenderTest < ActionController::TestCase end def test_should_implicitly_render_html_template_from_xhr_request - get :render_implicit_html_template_from_xhr_request, :format => :js - assert_equal "Hello HTML!", @response.body + xhr :get, :render_implicit_html_template_from_xhr_request + assert_equal "XHR!\nHello HTML!", @response.body + end + + def test_should_render_explicit_html_template_with_html_layout + xhr :get, :render_html_explicit_template_and_layout + assert_equal "<html>Hello HTML!</html>\n", @response.body end def test_should_implicitly_render_js_template_without_layout @@ -1115,7 +1173,7 @@ class RenderTest < ActionController::TestCase end def test_bad_render_to_string_still_throws_exception - assert_raises(ActionView::MissingTemplate) { get :render_to_string_with_exception } + assert_raise(ActionView::MissingTemplate) { get :render_to_string_with_exception } end def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns @@ -1140,15 +1198,15 @@ class RenderTest < ActionController::TestCase end def test_double_render - assert_raises(ActionController::DoubleRenderError) { get :double_render } + assert_raise(ActionController::DoubleRenderError) { get :double_render } end def test_double_redirect - assert_raises(ActionController::DoubleRenderError) { get :double_redirect } + assert_raise(ActionController::DoubleRenderError) { get :double_redirect } end def test_render_and_redirect - assert_raises(ActionController::DoubleRenderError) { get :render_and_redirect } + assert_raise(ActionController::DoubleRenderError) { get :render_and_redirect } end # specify the one exception to double render rule - render_to_string followed by render @@ -1429,6 +1487,16 @@ class RenderTest < ActionController::TestCase assert_equal "Sam\nmaS\n", @response.body end + def test_partial_with_nested_object + get :partial_with_nested_object + assert_equal "first", @response.body + end + + def test_partial_with_nested_object_shorthand + get :partial_with_nested_object_shorthand + assert_equal "first", @response.body + end + def test_hash_partial_collection get :partial_hash_collection assert_equal "Pratik\nkitarP\nAmy\nymA\n", @response.body @@ -1447,7 +1515,7 @@ class RenderTest < ActionController::TestCase end def test_render_missing_partial_template - assert_raises(ActionView::MissingTemplate) do + assert_raise(ActionView::MissingTemplate) do get :missing_partial end end @@ -1463,6 +1531,35 @@ class RenderTest < ActionController::TestCase end end +class ExpiresInRenderTest < ActionController::TestCase + tests TestController + + def setup + @request.host = "www.nextangle.com" + end + + def test_expires_in_header + get :conditional_hello_with_expires_in + assert_equal "max-age=60, private", @response.headers["Cache-Control"] + end + + def test_expires_in_header_with_public + get :conditional_hello_with_expires_in_with_public + assert_equal "max-age=60, public", @response.headers["Cache-Control"] + end + + def test_expires_in_header_with_additional_headers + get :conditional_hello_with_expires_in_with_public_with_more_keys + assert_equal "max-age=60, public, max-stale=18000", @response.headers["Cache-Control"] + end + + def test_expires_in_old_syntax + get :conditional_hello_with_expires_in_with_public_with_more_keys_old_syntax + assert_equal "max-age=60, public, max-stale=18000", @response.headers["Cache-Control"] + end +end + + class EtagRenderTest < ActionController::TestCase tests TestController @@ -1552,6 +1649,16 @@ class EtagRenderTest < ActionController::TestCase get :conditional_hello_with_bangs assert_response :not_modified end + + def test_etag_with_public_true_should_set_header + get :conditional_hello_with_public_header + assert_equal "public", @response.headers['Cache-Control'] + end + + def test_etag_with_public_true_should_set_header_and_retain_other_headers + get :conditional_hello_with_public_header_and_expires_at + assert_equal "max-age=60, public", @response.headers['Cache-Control'] + end protected def etag_for(text) diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index ef0bf5fd08..835e73e3ab 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -79,17 +79,17 @@ module RequestForgeryProtectionTests def test_should_not_allow_html_post_without_token @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raises(ActionController::InvalidAuthenticityToken) { post :index, :format => :html } + assert_raise(ActionController::InvalidAuthenticityToken) { post :index, :format => :html } end def test_should_not_allow_html_put_without_token @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raises(ActionController::InvalidAuthenticityToken) { put :index, :format => :html } + assert_raise(ActionController::InvalidAuthenticityToken) { put :index, :format => :html } end def test_should_not_allow_html_delete_without_token @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raises(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html } + assert_raise(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html } end def test_should_allow_api_formatted_post_without_token @@ -111,42 +111,42 @@ module RequestForgeryProtectionTests end def test_should_not_allow_api_formatted_post_sent_as_url_encoded_form_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s post :index, :format => 'xml' end end def test_should_not_allow_api_formatted_put_sent_as_url_encoded_form_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s put :index, :format => 'xml' end end def test_should_not_allow_api_formatted_delete_sent_as_url_encoded_form_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s delete :index, :format => 'xml' end end def test_should_not_allow_api_formatted_post_sent_as_multipart_form_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s post :index, :format => 'xml' end end def test_should_not_allow_api_formatted_put_sent_as_multipart_form_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s put :index, :format => 'xml' end end def test_should_not_allow_api_formatted_delete_sent_as_multipart_form_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + assert_raise(ActionController::InvalidAuthenticityToken) do @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s delete :index, :format => 'xml' end diff --git a/actionpack/test/controller/request_test.rb b/actionpack/test/controller/request_test.rb index efe4f136f5..c72f885a05 100644 --- a/actionpack/test/controller/request_test.rb +++ b/actionpack/test/controller/request_test.rb @@ -59,7 +59,7 @@ class RequestTest < ActiveSupport::TestCase assert_equal '3.4.5.6', @request.remote_ip @request.env['HTTP_CLIENT_IP'] = '8.8.8.8' - e = assert_raises(ActionController::ActionControllerError) { + e = assert_raise(ActionController::ActionControllerError) { @request.remote_ip } assert_match /IP spoofing attack/, e.message @@ -297,7 +297,7 @@ class RequestTest < ActiveSupport::TestCase end def test_invalid_http_method_raises_exception - assert_raises(ActionController::UnknownHttpMethod) do + assert_raise(ActionController::UnknownHttpMethod) do self.request_method = :random_method @request.request_method end @@ -311,7 +311,7 @@ class RequestTest < ActiveSupport::TestCase end def test_invalid_method_hacking_on_post_raises_exception - assert_raises(ActionController::UnknownHttpMethod) do + assert_raise(ActionController::UnknownHttpMethod) do self.request_method = :_random_method @request.request_method end diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index ae2639d245..35f943737f 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -99,7 +99,7 @@ class ResourcesTest < ActionController::TestCase expected_options = {:controller => 'messages', :action => 'show', :id => '1.1.1'} with_restful_routing :messages do - assert_raises(ActionController::RoutingError) do + assert_raise(ActionController::RoutingError) do assert_recognizes(expected_options, :path => 'messages/1.1.1', :method => :get) end end @@ -209,6 +209,14 @@ class ResourcesTest < ActionController::TestCase end end + def test_with_member_action_and_requirement + expected_options = {:controller => 'messages', :action => 'mark', :id => '1.1.1'} + + with_restful_routing(:messages, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}, :member => { :mark => :get }) do + assert_recognizes(expected_options, :path => 'messages/1.1.1/mark', :method => :get) + end + end + def test_member_when_override_paths_for_default_restful_actions_with [:put, :post].each do |method| with_restful_routing :messages, :member => { :mark => method }, :path_names => {:new => 'nuevo'} do @@ -325,7 +333,7 @@ class ResourcesTest < ActionController::TestCase with_restful_routing :messages do assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get) - assert_raises(ActionController::MethodNotAllowed) do + assert_raise(ActionController::MethodNotAllowed) do ActionController::Routing::Routes.recognize_path("/messages/new", :method => :post) end end @@ -406,6 +414,34 @@ class ResourcesTest < ActionController::TestCase end end + def test_shallow_nested_restful_routes_with_namespaces + with_routing do |set| + set.draw do |map| + map.namespace :backoffice do |map| + map.namespace :admin do |map| + map.resources :products, :shallow => true do |map| + map.resources :images + end + end + end + end + + assert_simply_restful_for :products, + :controller => 'backoffice/admin/products', + :namespace => 'backoffice/admin/', + :name_prefix => 'backoffice_admin_', + :path_prefix => 'backoffice/admin/', + :shallow => true + assert_simply_restful_for :images, + :controller => 'backoffice/admin/images', + :namespace => 'backoffice/admin/', + :name_prefix => 'backoffice_admin_product_', + :path_prefix => 'backoffice/admin/products/1/', + :shallow => true, + :options => { :product_id => '1' } + end + end + def test_restful_routes_dont_generate_duplicates with_restful_routing :messages do routes = ActionController::Routing::Routes.routes @@ -583,11 +619,11 @@ class ResourcesTest < ActionController::TestCase options = { :controller => controller_name.to_s } collection_path = "/#{controller_name}" - assert_raises(ActionController::MethodNotAllowed) do + assert_raise(ActionController::MethodNotAllowed) do assert_recognizes(options.merge(:action => 'update'), :path => collection_path, :method => :put) end - assert_raises(ActionController::MethodNotAllowed) do + assert_raise(ActionController::MethodNotAllowed) do assert_recognizes(options.merge(:action => 'destroy'), :path => collection_path, :method => :delete) end end @@ -596,7 +632,7 @@ class ResourcesTest < ActionController::TestCase def test_should_not_allow_invalid_head_method_for_member_routes with_routing do |set| set.draw do |map| - assert_raises(ArgumentError) do + assert_raise(ArgumentError) do map.resources :messages, :member => {:something => :head} end end @@ -606,7 +642,7 @@ class ResourcesTest < ActionController::TestCase def test_should_not_allow_invalid_http_methods_for_member_routes with_routing do |set| set.draw do |map| - assert_raises(ArgumentError) do + assert_raise(ArgumentError) do map.resources :messages, :member => {:something => :invalid} end end @@ -750,9 +786,17 @@ class ResourcesTest < ActionController::TestCase end def test_with_path_segment - with_restful_routing :messages, :as => 'reviews' do - assert_simply_restful_for :messages, :as => 'reviews' + with_restful_routing :messages do + assert_simply_restful_for :messages + assert_recognizes({:controller => "messages", :action => "index"}, "/messages") + assert_recognizes({:controller => "messages", :action => "index"}, "/messages/") end + + with_restful_routing :messages, :as => 'reviews' do + assert_simply_restful_for :messages, :as => 'reviews' + assert_recognizes({:controller => "messages", :action => "index"}, "/reviews") + assert_recognizes({:controller => "messages", :action => "index"}, "/reviews/") + end end def test_multiple_with_path_segment_and_controller @@ -1066,7 +1110,7 @@ class ResourcesTest < ActionController::TestCase path = "#{options[:as] || controller_name}" collection_path = "/#{options[:path_prefix]}#{path}" - shallow_path = "/#{options[:path_prefix] unless options[:shallow]}#{path}" + shallow_path = "/#{options[:shallow] ? options[:namespace] : options[:path_prefix]}#{path}" member_path = "#{shallow_path}/1" new_path = "#{collection_path}/#{new_action}" edit_member_path = "#{member_path}/#{edit_action}" @@ -1130,10 +1174,10 @@ class ResourcesTest < ActionController::TestCase options[:options].delete :action path = "#{options[:as] || controller_name}" - shallow_path = "/#{options[:path_prefix] unless options[:shallow]}#{path}" + shallow_path = "/#{options[:shallow] ? options[:namespace] : options[:path_prefix]}#{path}" full_path = "/#{options[:path_prefix]}#{path}" name_prefix = options[:name_prefix] - shallow_prefix = "#{options[:name_prefix] unless options[:shallow]}" + shallow_prefix = options[:shallow] ? options[:namespace].try(:gsub, /\//, '_') : options[:name_prefix] new_action = "new" edit_action = "edit" diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 13ba0c30dd..ef56119751 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -219,7 +219,7 @@ class DynamicSegmentTest < Test::Unit::TestCase a_value = nil # Local jump because of return inside eval. - assert_raises(LocalJumpError) { eval(segment.extraction_code) } + assert_raise(LocalJumpError) { eval(segment.extraction_code) } end def test_extraction_code_should_return_on_mismatch @@ -229,7 +229,7 @@ class DynamicSegmentTest < Test::Unit::TestCase a_value = nil # Local jump because of return inside eval. - assert_raises(LocalJumpError) { eval(segment.extraction_code) } + assert_raise(LocalJumpError) { eval(segment.extraction_code) } end def test_extraction_code_should_accept_value_and_set_local @@ -494,7 +494,7 @@ class RouteBuilderTest < Test::Unit::TestCase defaults = {:action => 'buy', :person => nil, :car => nil} requirements = {:person => /\w+/, :car => /^\w+$/} - assert_raises ArgumentError do + assert_raise ArgumentError do route_requirements = builder.assign_route_options(segments, defaults, requirements) end @@ -882,7 +882,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase end assert_equal({:controller => "admin/accounts", :action => "index"}, rs.recognize_path("/admin/accounts")) assert_equal({:controller => "admin/users", :action => "index"}, rs.recognize_path("/admin/users")) - assert_raises(ActionController::RoutingError) { rs.recognize_path("/admin/products") } + assert_raise(ActionController::RoutingError) { rs.recognize_path("/admin/products") } end def test_route_with_regexp_and_dot @@ -955,6 +955,13 @@ class LegacyRouteSetTests < Test::Unit::TestCase x.send(:page_url)) end + def test_named_route_with_blank_path_prefix + rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => '' + x = setup_for_named_route + assert_equal("http://test.host/page", + x.send(:page_url)) + end + def test_named_route_with_nested_controller rs.add_named_route :users, 'admin/user', :controller => 'admin/user', :action => 'index' x = setup_for_named_route @@ -1060,11 +1067,11 @@ class LegacyRouteSetTests < Test::Unit::TestCase rs.draw do |map| map.connect ':controller/:action/:id' end - assert_raises(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") } + assert_raise(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") } end def test_paths_do_not_accept_defaults - assert_raises(ActionController::RoutingError) do + assert_raise(ActionController::RoutingError) do rs.draw do |map| map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default) map.connect ':controller/:action/:id' @@ -1197,7 +1204,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10) - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do rs.generate(:controller => 'post', :action => 'show') end end @@ -1407,7 +1414,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase end x = setup_for_named_route - assert_raises(ActionController::RoutingError) do + assert_raise(ActionController::RoutingError) do x.send(:foo_with_requirement_url, "I am Against the requirements") end end @@ -1539,7 +1546,7 @@ class RouteTest < Test::Unit::TestCase end def test_builder_complains_without_controller - assert_raises(ArgumentError) do + assert_raise(ArgumentError) do ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index" end end @@ -1822,27 +1829,27 @@ class RouteSetTest < Test::Unit::TestCase end def test_route_requirements_with_anchor_chars_are_invalid - assert_raises ArgumentError do + assert_raise ArgumentError do set.draw do |map| map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+/ end end - assert_raises ArgumentError do + assert_raise ArgumentError do set.draw do |map| map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+/ end end - assert_raises ArgumentError do + assert_raise ArgumentError do set.draw do |map| map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+$/ end end - assert_raises ArgumentError do + assert_raise ArgumentError do set.draw do |map| map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z/ end end - assert_raises ArgumentError do + assert_raise ArgumentError do set.draw do |map| map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z/ end @@ -1851,22 +1858,30 @@ class RouteSetTest < Test::Unit::TestCase set.draw do |map| map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/, :name => /^(david|jamis)/ end - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do set.generate :controller => 'pages', :action => 'show', :id => 10 end end end def test_route_requirements_with_invalid_http_method_is_invalid - assert_raises ArgumentError do + assert_raise ArgumentError do set.draw do |map| map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :invalid} end end end + def test_route_requirements_with_options_method_condition_is_valid + assert_nothing_raised do + set.draw do |map| + map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :options} + end + end + end + def test_route_requirements_with_head_method_condition_is_invalid - assert_raises ArgumentError do + assert_raise ArgumentError do set.draw do |map| map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head} end @@ -1878,10 +1893,10 @@ class RouteSetTest < Test::Unit::TestCase map.connect 'page/37s', :controller => 'pages', :action => 'show', :name => /(jamis|david)/ end assert_equal '/page/37s', set.generate(:controller => 'pages', :action => 'show', :name => 'jamis') - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do set.generate(:controller => 'pages', :action => 'show', :name => 'not_jamis') end - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do set.generate(:controller => 'pages', :action => 'show', :name => 'nor_jamis_and_david') end end @@ -1924,7 +1939,7 @@ class RouteSetTest < Test::Unit::TestCase assert_equal("update", request.path_parameters[:action]) request.recycle! - assert_raises(ActionController::UnknownHttpMethod) { + assert_raise(ActionController::UnknownHttpMethod) { request.env["REQUEST_METHOD"] = "BACON" set.recognize(request) } @@ -2122,11 +2137,9 @@ class RouteSetTest < Test::Unit::TestCase Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) }) set.draw do |map| - map.namespace 'api', :path_prefix => 'prefix' do |api| api.route 'inventory', :controller => "products", :action => 'inventory' end - end request.path = "/prefix/inventory" @@ -2138,6 +2151,24 @@ class RouteSetTest < Test::Unit::TestCase Object.send(:remove_const, :Api) end + def test_namespace_with_blank_path_prefix + Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) }) + + set.draw do |map| + map.namespace 'api', :path_prefix => '' do |api| + api.route 'inventory', :controller => "products", :action => 'inventory' + end + end + + request.path = "/inventory" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("api/products", request.path_parameters[:controller]) + assert_equal("inventory", request.path_parameters[:action]) + ensure + Object.send(:remove_const, :Api) + end + def test_generate_finds_best_fit set.draw do |map| map.connect "/people", :controller => "people", :action => "index" @@ -2202,6 +2233,13 @@ class RouteSetTest < Test::Unit::TestCase assert_equal "/my/foo/bar/7?x=y", set.generate(args) end + def test_generate_with_blank_path_prefix + set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => '' } + + args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" } + assert_equal "/foo/bar/7?x=y", set.generate(args) + end + def test_named_routes_are_never_relative_to_modules set.draw do |map| map.connect "/connection/manage/:action", :controller => 'connection/manage' @@ -2237,6 +2275,22 @@ class RouteSetTest < Test::Unit::TestCase ) end + def test_format_is_not_inherit + set.draw do |map| + map.connect '/posts.:format', :controller => 'posts' + end + + assert_equal '/posts', set.generate( + {:controller => 'posts'}, + {:controller => 'posts', :action => 'index', :format => 'xml'} + ) + + assert_equal '/posts.xml', set.generate( + {:controller => 'posts', :format => 'xml'}, + {:controller => 'posts', :action => 'index', :format => 'xml'} + ) + end + def test_expiry_determination_should_consider_values_with_to_param set.draw { |map| map.connect 'projects/:project_id/:controller/:action' } assert_equal '/projects/1/post/show', set.generate( @@ -2293,7 +2347,7 @@ class RouteSetTest < Test::Unit::TestCase end def test_route_requirements_with_unsupported_regexp_options_must_error - assert_raises ArgumentError do + assert_raise ArgumentError do set.draw do |map| map.connect 'page/:name', :controller => 'pages', :action => 'show', @@ -2331,7 +2385,7 @@ class RouteSetTest < Test::Unit::TestCase :requirements => {:name => /(david|jamis)/i} end assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis')) - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do set.recognize_path('/page/davidjamis') end assert_equal({:controller => 'pages', :action => 'show', :name => 'DAVID'}, set.recognize_path('/page/DAVID')) @@ -2345,7 +2399,7 @@ class RouteSetTest < Test::Unit::TestCase end url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'}) assert_equal "/page/david", url - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'}) end url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) @@ -2365,10 +2419,10 @@ class RouteSetTest < Test::Unit::TestCase end assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis')) assert_equal({:controller => 'pages', :action => 'show', :name => 'david'}, set.recognize_path('/page/david')) - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do set.recognize_path('/page/david #The Creator') end - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do set.recognize_path('/page/David') end end @@ -2386,10 +2440,10 @@ class RouteSetTest < Test::Unit::TestCase end url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'}) assert_equal "/page/david", url - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'}) end - assert_raises ActionController::RoutingError do + assert_raise ActionController::RoutingError do url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) end end diff --git a/actionpack/test/controller/selector_test.rb b/actionpack/test/controller/selector_test.rb index 4e31b4573c..9d0613d1e2 100644 --- a/actionpack/test/controller/selector_test.rb +++ b/actionpack/test/controller/selector_test.rb @@ -303,7 +303,7 @@ class SelectorTest < Test::Unit::TestCase assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] # Before first and past last returns nothing.: - assert_raises(ArgumentError) { select("tr:nth-child(-1)") } + assert_raise(ArgumentError) { select("tr:nth-child(-1)") } select("tr:nth-child(0)") assert_equal 0, @matches.size select("tr:nth-child(5)") @@ -597,8 +597,8 @@ class SelectorTest < Test::Unit::TestCase def test_negation_details parse(%Q{<p id="1"></p><p id="2"></p><p id="3"></p>}) - assert_raises(ArgumentError) { select(":not(") } - assert_raises(ArgumentError) { select(":not(:not())") } + assert_raise(ArgumentError) { select(":not(") } + assert_raise(ArgumentError) { select(":not(:not())") } select("p:not(#1):not(#3)") assert_equal 1, @matches.size assert_equal "2", @matches[0].attributes["id"] diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index 5fc79baa44..a27e951929 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -142,7 +142,7 @@ class SendFileTest < ActionController::TestCase } @controller.headers = {} - assert_raises(ArgumentError){ @controller.send(:send_file_headers!, options) } + assert_raise(ArgumentError){ @controller.send(:send_file_headers!, options) } end %w(file data).each do |method| diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb index 09a8356fec..863f8414c5 100644 --- a/actionpack/test/controller/url_rewriter_test.rb +++ b/actionpack/test/controller/url_rewriter_test.rb @@ -99,7 +99,7 @@ class UrlWriterTests < ActionController::TestCase end def test_exception_is_thrown_without_host - assert_raises RuntimeError do + assert_raise RuntimeError do W.new.url_for :controller => 'c', :action => 'a', :id => 'i' end end diff --git a/actionpack/test/fixtures/layouts/default_html.html.erb b/actionpack/test/fixtures/layouts/default_html.html.erb new file mode 100644 index 0000000000..edd719111c --- /dev/null +++ b/actionpack/test/fixtures/layouts/default_html.html.erb @@ -0,0 +1 @@ +<html><%= @content_for_layout %></html> diff --git a/actionpack/test/fixtures/layouts/xhr.html.erb b/actionpack/test/fixtures/layouts/xhr.html.erb new file mode 100644 index 0000000000..85285324ec --- /dev/null +++ b/actionpack/test/fixtures/layouts/xhr.html.erb @@ -0,0 +1,2 @@ +XHR! +<%= yield %>
\ No newline at end of file diff --git a/actionpack/test/fixtures/quiz/questions/_question.html.erb b/actionpack/test/fixtures/quiz/questions/_question.html.erb new file mode 100644 index 0000000000..fb4dcfee64 --- /dev/null +++ b/actionpack/test/fixtures/quiz/questions/_question.html.erb @@ -0,0 +1 @@ +<%= question.name %>
\ No newline at end of file diff --git a/actionpack/test/fixtures/test/malformed/malformed.en.html.erb~ b/actionpack/test/fixtures/test/malformed/malformed.en.html.erb~ new file mode 100644 index 0000000000..d009950384 --- /dev/null +++ b/actionpack/test/fixtures/test/malformed/malformed.en.html.erb~ @@ -0,0 +1 @@ +Don't render me!
\ No newline at end of file diff --git a/actionpack/test/fixtures/test/malformed/malformed.erb~ b/actionpack/test/fixtures/test/malformed/malformed.erb~ new file mode 100644 index 0000000000..d009950384 --- /dev/null +++ b/actionpack/test/fixtures/test/malformed/malformed.erb~ @@ -0,0 +1 @@ +Don't render me!
\ No newline at end of file diff --git a/actionpack/test/fixtures/test/malformed/malformed.html.erb~ b/actionpack/test/fixtures/test/malformed/malformed.html.erb~ new file mode 100644 index 0000000000..d009950384 --- /dev/null +++ b/actionpack/test/fixtures/test/malformed/malformed.html.erb~ @@ -0,0 +1 @@ +Don't render me!
\ No newline at end of file diff --git a/actionpack/test/template/active_record_helper_test.rb b/actionpack/test/template/active_record_helper_test.rb index e46f95d18b..83c028b5f2 100644 --- a/actionpack/test/template/active_record_helper_test.rb +++ b/actionpack/test/template/active_record_helper_test.rb @@ -19,6 +19,30 @@ class ActiveRecordHelperTest < ActionView::TestCase Column = Struct.new("Column", :type, :name, :human_name) end + class DirtyPost + class Errors + def empty? + false + end + + def count + 1 + end + + def full_messages + ["Author name can't be <em>empty</em>"] + end + + def on(field) + "can't be <em>empty</em>" + end + end + + def errors + Errors.new + end + end + def setup_post @post = Post.new def @post.errors @@ -195,10 +219,20 @@ class ActiveRecordHelperTest < ActionView::TestCase assert_equal %(<div class="errorDeathByClass"><h1>1 error prohibited this post from being saved</h1><p>There were problems with the following fields:</p><ul><li>Author name can't be empty</li></ul></div>), error_messages_for("post", :class => "errorDeathByClass", :id => nil, :header_tag => "h1") end + def test_error_messages_for_escapes_html + @dirty_post = DirtyPost.new + assert_dom_equal %(<div class="errorExplanation" id="errorExplanation"><h2>1 error prohibited this dirty post from being saved</h2><p>There were problems with the following fields:</p><ul><li>Author name can't be <em>empty</em></li></ul></div>), error_messages_for("dirty_post") + end + def test_error_messages_for_handles_nil assert_equal "", error_messages_for("notthere") end + def test_error_message_on_escapes_html + @dirty_post = DirtyPost.new + assert_dom_equal "<div class=\"formError\">can't be <em>empty</em></div>", error_message_on(:dirty_post, :author_name) + end + def test_error_message_on_handles_nil assert_equal "", error_message_on("notthere", "notthere") end diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 5cc81b4afb..654eee40a3 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -1001,6 +1001,47 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_form_for_with_labelled_builder_with_nested_fields_for_without_options_hash + klass = nil + + form_for(:post, @post, :builder => LabelledFormBuilder) do |f| + f.fields_for(:comments, Comment.new) do |nested_fields| + klass = nested_fields.class + '' + end + end + + assert_equal LabelledFormBuilder, klass + end + + def test_form_for_with_labelled_builder_with_nested_fields_for_with_options_hash + klass = nil + + form_for(:post, @post, :builder => LabelledFormBuilder) do |f| + f.fields_for(:comments, Comment.new, :index => 'foo') do |nested_fields| + klass = nested_fields.class + '' + end + end + + assert_equal LabelledFormBuilder, klass + end + + class LabelledFormBuilderSubclass < LabelledFormBuilder; end + + def test_form_for_with_labelled_builder_with_nested_fields_for_with_custom_builder + klass = nil + + form_for(:post, @post, :builder => LabelledFormBuilder) do |f| + f.fields_for(:comments, Comment.new, :builder => LabelledFormBuilderSubclass) do |nested_fields| + klass = nested_fields.class + '' + end + end + + assert_equal LabelledFormBuilderSubclass, klass + end + def test_form_for_with_html_options_adds_options_to_form_tag form_for(:post, @post, :html => {:id => 'some_form', :class => 'some_class'}) do |f| end expected = "<form action=\"http://www.example.com\" class=\"some_class\" id=\"some_form\" method=\"post\"></form>" diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index 0c8af60aa4..c713b8da8e 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -266,11 +266,18 @@ class FormTagHelperTest < ActionView::TestCase def test_submit_tag_with_confirmation assert_dom_equal( - %(<input name='commit' type='submit' value='Save' onclick="return confirm('Are you sure?');"/>), + %(<input name='commit' type='submit' value='Save' onclick="if (!confirm('Are you sure?')) return false; return true;"/>), submit_tag("Save", :confirm => "Are you sure?") ) end - + + def test_submit_tag_with_confirmation_and_with_disable_with + assert_dom_equal( + %(<input name="commit" type="submit" value="Save" onclick="if (!confirm('Are you sure?')) return false; if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = this.cloneNode(false);hiddenCommit.setAttribute('type', 'hidden');this.form.appendChild(hiddenCommit); }this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Saving...';result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute('originalValue');this.disabled = false; }return result;" />), + submit_tag("Save", :disable_with => "Saving...", :confirm => "Are you sure?") + ) + end + def test_image_submit_tag_with_confirmation assert_dom_equal( %(<input type="image" src="/images/save.gif" onclick="return confirm('Are you sure?');"/>), diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb index d41111127b..d2fb24e36e 100644 --- a/actionpack/test/template/javascript_helper_test.rb +++ b/actionpack/test/template/javascript_helper_test.rb @@ -45,11 +45,6 @@ class JavaScriptHelperTest < ActionView::TestCase link_to_function("Greeting", "alert('Hello world!')", :href => 'http://example.com/') end - def test_link_to_function_with_href - assert_dom_equal %(<a href="http://example.com/" onclick="alert('Hello world!'); return false;">Greeting</a>), - link_to_function("Greeting", "alert('Hello world!')", :href => 'http://example.com/') - end - def test_button_to_function assert_dom_equal %(<input type="button" onclick="alert('Hello world!');" value="Greeting" />), button_to_function("Greeting", "alert('Hello world!')") diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb index 9c9f54936c..29cb60fd73 100644 --- a/actionpack/test/template/number_helper_test.rb +++ b/actionpack/test/template/number_helper_test.rb @@ -4,6 +4,7 @@ class NumberHelperTest < ActionView::TestCase tests ActionView::Helpers::NumberHelper def test_number_to_phone + assert_equal("555-1234", number_to_phone(5551234)) assert_equal("800-555-1212", number_to_phone(8005551212)) assert_equal("(800) 555-1212", number_to_phone(8005551212, {:area_code => true})) assert_equal("800 555 1212", number_to_phone(8005551212, {:delimiter => " "})) diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index 107c625e32..9adf053b09 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -145,6 +145,10 @@ module RenderTestCases assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name end + def test_render_object + assert_equal "Hello: david", @view.render(:partial => "test/customer", :object => Customer.new("david")) + end + def test_render_partial_collection assert_equal "Hello: davidHello: mary", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ]) end @@ -224,6 +228,16 @@ module RenderTestCases assert_equal 'source: Hello, <%= name %>!; locals: {:name=>"Josh"}', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo) end + def test_render_ignores_templates_with_malformed_template_handlers + %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name| + assert_raise(ActionView::MissingTemplate) { @view.render(:file => "test/malformed/#{name}") } + end + end + + def test_template_with_malformed_template_handler_is_reachable_through_its_exact_filename + assert_equal "Don't render me!", @view.render(:file => 'test/malformed/malformed.html.erb~') + end + def test_render_with_layout assert_equal %(<title></title>\nHello world!\n), @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield") diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index e7799fb204..5900709d81 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -220,7 +220,7 @@ class UrlHelperTest < ActionView::TestCase end def test_link_tag_using_post_javascript_and_popup - assert_raises(ActionView::ActionViewError) { link_to("Hello", "http://www.example.com", :popup => true, :method => :post, :confirm => "Are you serious?") } + assert_raise(ActionView::ActionViewError) { link_to("Hello", "http://www.example.com", :popup => true, :method => :post, :confirm => "Are you serious?") } end def test_link_tag_using_block_in_erb |