diff options
author | Carl Lerche & Yehuda Katz <wycats@gmail.com> | 2009-04-13 15:18:45 -0700 |
---|---|---|
committer | Carl Lerche & Yehuda Katz <wycats@gmail.com> | 2009-04-13 15:18:45 -0700 |
commit | 906aebceedb95d8caa6db6314bc90f605bdfaf2b (patch) | |
tree | 5abc86bb6709b20df7cb5f4d1750b27c641dca4b /actionpack | |
parent | 2036d3ba75da1a0f3061bf5a33c89e2b2eaff420 (diff) | |
parent | c877857d59554d78dbf45f5f9fcaafb8badec4e2 (diff) | |
download | rails-906aebceedb95d8caa6db6314bc90f605bdfaf2b.tar.gz rails-906aebceedb95d8caa6db6314bc90f605bdfaf2b.tar.bz2 rails-906aebceedb95d8caa6db6314bc90f605bdfaf2b.zip |
Bring abstract_controller up to date with rails/master
Resolved all the conflicts since 2.3.0 -> HEAD. Following is a list
of commits that could not be applied cleanly or are obviated with the
abstract_controller refactor. They all need to be revisited to ensure
that fixes made in 2.3 do not reappear in 3.0:
2259ecf368e6a6715966f69216e3ee86bf1a82a7
AR not available
* This will be reimplemented with ActionORM or equivalent
06182ea02e92afad579998aa80144588e8865ac3
implicitly rendering a js response should not use the default layout
[#1844 state:resolved]
* This will be handled generically
893e9eb99504705419ad6edac14d00e71cef5f12
Improve view rendering performance in development mode and reinstate
template recompiling in production [#1909 state:resolved]
* We will need to reimplement rails-dev-boost on top of the refactor;
the changes here are very implementation specific and cannot be
cleanly applied. The following commits are implicated:
199e750d46c04970b5e7684998d09405648ecbd4
3942cb406e1d5db0ac00e03153809cc8dc4cc4db
f8ea9f85d4f1e3e6f3b5d895bef6b013aa4b0690
e3b166aab37ddc2fbab030b146eb61713b91bf55
ae9f258e03c9fd5088da12c1c6cd216cc89a01f7
44423126c6f6133a1d9cf1d0832b527e8711d40f
0cb020b4d6d838025859bd60fb8151c8e21b8e84
workaround for picking layouts based on wrong view_paths
[#1974 state:resolved]
* The specifics of this commit no longer apply. Since it is a two-line
commit, we will reimplement this change.
8c5cc66a831aadb159f3daaffa4208064c30af0e
make action_controller/layouts pick templates from the current instance's
view_paths instead of the class view_paths [#1974 state:resolved]
* This does not apply at all. It should be trivial to apply the feature
to the reimplemented ActionController::Base.
87e8b162463f13bd50d27398f020769460a770e3
fix HTML fallback for explicit templates [#2052 state:resolved]
* There were a number of patches related to this that simply compounded
each other. Basically none of them apply cleanly, and the underlying
issue needs to be revisited. After discussing the underlying problem
with Koz, we will defer these fixes for further discussion.
Diffstat (limited to 'actionpack')
172 files changed, 10033 insertions, 3607 deletions
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index e9e18a8f6b..11ee1c1059 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,4 +1,35 @@ -*2.3.0 [Edge]* +*Edge* + +* Fixed that TestResponse.cookies was returning cookies unescaped #1867 [Doug McInnes] + + +*2.3.2 [Final] (March 15, 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] + +* Form option helpers now support disabled option tags and the use of lambdas for selecting/disabling option tags from collections #837 [Tekin] + +* 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] + +* Fix a syntax error in current_page?() that was prevent matches against URL's with multiple query parameters #1385, #1868 [chris finne/Andrew White] + +* Added localized rescue template when I18n.locale is set (ex: public/404.da.html) #1835 [José Valim] + +* Make the form_for and fields_for helpers support the new Active Record nested update options. #1202 [Eloy Duran] + + <% form_for @person do |person_form| %> + ... + <% person_form.fields_for :projects do |project_fields| %> + <% if project_fields.object.active? %> + Name: <%= project_fields.text_field :name %> + <% end %> + <% end %> + <% end %> + * Added grouped_options_for_select helper method for wrapping option tags in optgroups. #977 [Jon Crawford] diff --git a/actionpack/Rakefile b/actionpack/Rakefile index 230a78c069..300c2ebf81 100644 --- a/actionpack/Rakefile +++ b/actionpack/Rakefile @@ -80,8 +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('rack', '>= 0.9.0') + s.add_dependency('activesupport', '= 2.3.2' + PKG_BUILD) s.require_path = 'lib' s.autorequire = 'action_controller' diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb index eb596ba40e..e435bdbae1 100644 --- a/actionpack/lib/action_controller.rb +++ b/actionpack/lib/action_controller.rb @@ -32,6 +32,13 @@ rescue LoadError end require File.join(File.dirname(__FILE__), "action_pack") +$:.unshift "#{File.dirname(__FILE__)}/action_controller/vendor/rack-1.0" +begin + gem 'rack', '~> 1.0.0' + require 'rack' +rescue Gem::LoadError + require 'action_controller/vendor/rack-1.0/rack' +end module ActionController # TODO: Review explicit to see if they will automatically be handled by @@ -57,6 +64,7 @@ module ActionController autoload :PolymorphicRoutes, 'action_controller/routing/generation/polymorphic_routes' autoload :RecordIdentifier, 'action_controller/record_identifier' autoload :Redirector, 'action_controller/base/redirect' + autoload :Reloader, 'action_controller/reloader' autoload :Renderer, 'action_controller/base/render' autoload :RequestForgeryProtection, 'action_controller/base/request_forgery_protection' autoload :Rescue, 'action_controller/dispatch/rescue' @@ -72,6 +80,9 @@ module ActionController autoload :UrlRewriter, 'action_controller/routing/generation/url_rewriter' autoload :UrlWriter, 'action_controller/routing/generation/url_rewriter' autoload :Verification, 'action_controller/base/verification' + autoload :UploadedFile, 'action_dispatch/utils/uploaded_file' + autoload :UploadedStringIO, 'action_dispatch/utils/uploaded_file' + autoload :UploadedTempfile, 'action_dispatch/utils/uploaded_file' module Assertions autoload :DomAssertions, 'action_controller/testing/assertions/dom' diff --git a/actionpack/lib/action_controller/base/base.rb b/actionpack/lib/action_controller/base/base.rb index 7a745ea040..aea434ffa0 100644 --- a/actionpack/lib/action_controller/base/base.rb +++ b/actionpack/lib/action_controller/base/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 @@ -394,7 +394,7 @@ module ActionController #:nodoc: # Return an array containing the names of public methods that have been marked hidden from the action processor. # By default, all methods defined in ActionController::Base and included modules are hidden. - # More methods can be hidden using <tt>hide_actions</tt>. + # More methods can be hidden using <tt>hide_action</tt>. def hidden_actions read_inheritable_attribute(:hidden_actions) || write_inheritable_attribute(:hidden_actions, []) end @@ -690,6 +690,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 @@ -710,20 +715,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 @@ -735,15 +754,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 @@ -839,6 +869,7 @@ module ActionController #:nodoc: end end + # Returns true if a render or redirect has already been performed. def performed? @performed_render || @performed_redirect end @@ -857,6 +888,7 @@ module ActionController #:nodoc: @request_origin ||= "#{request.remote_ip} at #{Time.now.to_s(:db)}" end + # Returns the request URI used to get to the current location def complete_request_uri "#{request.protocol}#{request.host}#{request.request_uri}" end diff --git a/actionpack/lib/action_controller/base/cookies.rb b/actionpack/lib/action_controller/base/cookies.rb index 840ceb5abd..ca380e98d0 100644 --- a/actionpack/lib/action_controller/base/cookies.rb +++ b/actionpack/lib/action_controller/base/cookies.rb @@ -41,7 +41,7 @@ module ActionController #:nodoc: # * <tt>:expires</tt> - The time at which this cookie expires, as a Time object. # * <tt>:secure</tt> - Whether this cookie is a only transmitted to HTTPS servers. # Default is +false+. - # * <tt>:http_only</tt> - Whether this cookie is accessible via scripting or + # * <tt>:httponly</tt> - Whether this cookie is accessible via scripting or # only HTTP. Defaults to +false+. module Cookies def self.included(base) diff --git a/actionpack/lib/action_controller/base/http_authentication.rb b/actionpack/lib/action_controller/base/http_authentication.rb index 5d915fda08..b6b5267c66 100644 --- a/actionpack/lib/action_controller/base/http_authentication.rb +++ b/actionpack/lib/action_controller/base/http_authentication.rb @@ -68,8 +68,11 @@ module ActionController # # Simple Digest example: # + # require 'digest/md5' # class PostsController < ApplicationController - # USERS = {"dhh" => "secret"} + # REALM = "SuperSecret" + # USERS = {"dhh" => "secret", #plain text password + # "dap" => Digest:MD5::hexdigest(["dap",REALM,"secret"].join(":")) #ha1 digest password # # before_filter :authenticate, :except => [:index] # @@ -83,14 +86,18 @@ module ActionController # # private # def authenticate - # authenticate_or_request_with_http_digest(realm) do |username| + # authenticate_or_request_with_http_digest(REALM) do |username| # USERS[username] # end # end # end # - # NOTE: The +authenticate_or_request_with_http_digest+ block must return the user's password so the framework can appropriately - # hash it to check the user's credentials. Returning +nil+ will cause authentication to fail. + # NOTE: The +authenticate_or_request_with_http_digest+ block must return the user's password or the ha1 digest hash so the framework can appropriately + # hash to check the user's credentials. Returning +nil+ will cause authentication to fail. + # Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If + # the password file or database is compromised, the attacker would be able to use the ha1 hash to + # authenticate as the user at this +realm+, but would not have the user's password to try using at + # other sites. # # On shared hosts, Apache sometimes doesn't pass authentication headers to # FCGI instances. If your environment matches this description and you cannot @@ -177,26 +184,37 @@ module ActionController end # Raises error unless the request credentials response value matches the expected value. + # First try the password as a ha1 digest password. If this fails, then try it as a plain + # text password. def validate_digest_response(request, realm, &password_procedure) credentials = decode_credentials_header(request) valid_nonce = validate_nonce(request, credentials[:nonce]) - if valid_nonce && realm == credentials[:realm] && opaque(request.session.session_id) == credentials[:opaque] + if valid_nonce && realm == credentials[:realm] && opaque == credentials[:opaque] password = password_procedure.call(credentials[:username]) - expected = expected_response(request.env['REQUEST_METHOD'], request.url, credentials, password) - expected == credentials[:response] + + [true, false].any? do |password_is_ha1| + expected = expected_response(request.env['REQUEST_METHOD'], request.env['REQUEST_URI'], credentials, password, password_is_ha1) + expected == credentials[:response] + end end end # Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+ - def expected_response(http_method, uri, credentials, password) - ha1 = ::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':')) + # Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead + # of a plain-text password. + def expected_response(http_method, uri, credentials, password, password_is_ha1=true) + ha1 = password_is_ha1 ? password : ha1(credentials, password) ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':')) ::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':')) end - def encode_credentials(http_method, credentials, password) - credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password) + def ha1(credentials, password) + ::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':')) + end + + def encode_credentials(http_method, credentials, password, password_is_ha1) + credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1) "Digest " + credentials.sort_by {|x| x[0].to_s }.inject([]) {|a, v| a << "#{v[0]}='#{v[1]}'" }.join(', ') end @@ -213,8 +231,7 @@ module ActionController end def authentication_header(controller, realm) - session_id = controller.request.session.session_id - controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce(session_id)}", opaque="#{opaque(session_id)}") + controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}") end def authentication_request(controller, realm, message = nil) @@ -252,23 +269,36 @@ module ActionController # POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4 # of this document. # - # The nonce is opaque to the client. - def nonce(session_id, time = Time.now) + # The nonce is opaque to the client. Composed of Time, and hash of Time with secret + # key from the Rails session secret generated upon creation of project. Ensures + # the time cannot be modifed by client. + def nonce(time = Time.now) t = time.to_i - hashed = [t, session_id] + hashed = [t, secret_key] digest = ::Digest::MD5.hexdigest(hashed.join(":")) Base64.encode64("#{t}:#{digest}").gsub("\n", '') end - def validate_nonce(request, value) + # Might want a shorter timeout depending on whether the request + # is a PUT or POST, and if client is browser or web service. + # Can be much shorter if the Stale directive is implemented. This would + # allow a user to use new nonce without prompting user again for their + # username and password. + def validate_nonce(request, value, seconds_to_timeout=5*60) t = Base64.decode64(value).split(":").first.to_i - nonce(request.session.session_id, t) == value && (t - Time.now.to_i).abs <= 10 * 60 + nonce(t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout end - # Opaque based on digest of session_id - def opaque(session_id) - Base64.encode64(::Digest::MD5::hexdigest(session_id)).gsub("\n", '') + # Opaque based on random generation - but changing each request? + def opaque() + ::Digest::MD5.hexdigest(secret_key) end + + # Set in /initializers/session_store.rb, and loaded even if sessions are not in use. + def secret_key + ActionController::Base.session_options[:secret] + end + end end end diff --git a/actionpack/lib/action_controller/base/redirect.rb b/actionpack/lib/action_controller/base/redirect.rb index 83af793978..2e92117e7c 100644 --- a/actionpack/lib/action_controller/base/redirect.rb +++ b/actionpack/lib/action_controller/base/redirect.rb @@ -49,7 +49,6 @@ module ActionController 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 @@ -72,6 +71,7 @@ module ActionController 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 diff --git a/actionpack/lib/action_controller/base/render.rb b/actionpack/lib/action_controller/base/render.rb index abba059969..c4a3725079 100644 --- a/actionpack/lib/action_controller/base/render.rb +++ b/actionpack/lib/action_controller/base/render.rb @@ -197,7 +197,17 @@ module ActionController raise DoubleRenderError, "Can only render or redirect once per action" if performed? options = { :layout => true } if options.nil? - original, options = options, extra_options unless options.is_a?(Hash) + + # This handles render "string", render :symbol, and render object + # render string and symbol are handled by render_for_name + # render object becomes render :partial => object + unless options.is_a?(Hash) + if options.is_a?(String) || options.is_a?(Symbol) + original, options = options, extra_options + else + extra_options[:partial], options = options, extra_options + end + end layout_name = options.delete(:layout) @@ -300,6 +310,7 @@ module ActionController # of sending it as the response body to the browser. def render_to_string(options = nil, &block) #:doc: render(options, &block) + response.body ensure response.content_type = nil erase_render_results @@ -308,7 +319,7 @@ module ActionController # Clears the rendered results, allowing for another render to be performed. def erase_render_results #:nodoc: - response.body = nil + response.body = [] @performed_render = false end @@ -360,8 +371,9 @@ module ActionController def render_for_parts(parts, layout, options = {}) tmp = view_paths.find_by_parts(*parts) - layout = _pick_layout(*layout) unless tmp.exempt_from_layout? + layout = _pick_layout(*layout) unless tmp.exempt_from_layout? + render_for_text( @template._render_template_with_layout(tmp, layout, options, parts[3])) end diff --git a/actionpack/lib/action_controller/base/responder.rb b/actionpack/lib/action_controller/base/responder.rb index f83abb5a4b..989f82444b 100644 --- a/actionpack/lib/action_controller/base/responder.rb +++ b/actionpack/lib/action_controller/base/responder.rb @@ -20,6 +20,7 @@ module ActionController end end + # Returns a set of the methods defined as actions in your controller def action_methods self.class.action_methods end diff --git a/actionpack/lib/action_controller/base/streaming.rb b/actionpack/lib/action_controller/base/streaming.rb index e1786913a7..9f80f48c3d 100644 --- a/actionpack/lib/action_controller/base/streaming.rb +++ b/actionpack/lib/action_controller/base/streaming.rb @@ -1,5 +1,6 @@ module ActionController #:nodoc: - # Methods for sending files and streams to the browser instead of rendering. + # Methods for sending arbitrary data and for streaming files to the browser, + # instead of rendering. module Streaming DEFAULT_SEND_FILE_OPTIONS = { :type => 'application/octet-stream'.freeze, @@ -103,8 +104,11 @@ module ActionController #:nodoc: end end - # Send binary data to the user as a file download. May set content type, apparent file name, - # and specify whether to show data inline or download as an attachment. + # Sends the given binary data to the browser. This method is similar to + # <tt>render :text => data</tt>, but also allows you to specify whether + # the browser should display the response as a file attachment (i.e. in a + # download dialog) or as inline data. You may also set the content type, + # the apparent file name, and other things. # # Options: # * <tt>:filename</tt> - suggests a filename for the browser to use. @@ -127,6 +131,10 @@ module ActionController #:nodoc: # send_data image.data, :type => image.content_type, :disposition => 'inline' # # See +send_file+ for more information on HTTP Content-* headers and caching. + # + # <b>Tip:</b> if you want to stream large amounts of on-the-fly generated + # data to the browser, then use <tt>render :text => proc { ... }</tt> + # instead. See ActionController::Base#render for more information. def send_data(data, options = {}) #:doc: logger.info "Sending data #{options[:filename]}" if logger send_file_headers! options.merge(:length => data.size) @@ -152,7 +160,7 @@ module ActionController #:nodoc: end content_type = content_type.to_s.strip # fixes a problem with extra '\r' with some browsers - headers.update( + headers.merge!( 'Content-Length' => options[:length], 'Content-Type' => content_type, 'Content-Disposition' => disposition, diff --git a/actionpack/lib/action_controller/base/verification.rb b/actionpack/lib/action_controller/base/verification.rb index 7bf09ba6ea..c62b81b666 100644 --- a/actionpack/lib/action_controller/base/verification.rb +++ b/actionpack/lib/action_controller/base/verification.rb @@ -90,7 +90,7 @@ module ActionController #:nodoc: def verify_action(options) #:nodoc: if prereqs_invalid?(options) flash.update(options[:add_flash]) if options[:add_flash] - response.headers.update(options[:add_headers]) if options[:add_headers] + response.headers.merge!(options[:add_headers]) if options[:add_headers] apply_remaining_actions(options) unless performed? end end diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb index 1d14df0052..80d13e25f1 100644 --- a/actionpack/lib/action_controller/caching.rb +++ b/actionpack/lib/action_controller/caching.rb @@ -27,6 +27,7 @@ module ActionController #:nodoc: autoload :Actions, 'action_controller/caching/actions' autoload :Fragments, 'action_controller/caching/fragments' autoload :Pages, 'action_controller/caching/pages' + autoload :Sweeper, 'action_controller/caching/sweeping' autoload :Sweeping, 'action_controller/caching/sweeping' def self.included(base) #:nodoc: diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb index 34e1c3527f..87b5029e57 100644 --- a/actionpack/lib/action_controller/caching/actions.rb +++ b/actionpack/lib/action_controller/caching/actions.rb @@ -129,24 +129,23 @@ module ActionController #:nodoc: attr_reader :path, :extension class << self - def path_for(controller, options, infer_extension=true) + def path_for(controller, options, infer_extension = true) new(controller, options, infer_extension).path end end # When true, infer_extension will look up the cache path extension from the request's path & format. - # This is desirable when reading and writing the cache, but not when expiring the cache - expire_action should expire the same files regardless of the request format. - def initialize(controller, options = {}, infer_extension=true) - if infer_extension and options.is_a? Hash - request_extension = extract_extension(controller.request) - options = options.reverse_merge(:format => request_extension) + # This is desirable when reading and writing the cache, but not when expiring the cache - + # expire_action should expire the same files regardless of the request format. + def initialize(controller, options = {}, infer_extension = true) + if infer_extension + extract_extension(controller.request) + options = options.reverse_merge(:format => @extension) if options.is_a?(Hash) end + path = controller.url_for(options).split('://').last normalize!(path) - if infer_extension - @extension = request_extension - add_extension!(path, @extension) - end + add_extension!(path, @extension) @path = URI.unescape(path) end @@ -162,13 +161,7 @@ module ActionController #:nodoc: def extract_extension(request) # Don't want just what comes after the last '.' to accommodate multi part extensions # such as tar.gz. - extension = request.path[/^[^.]+\.(.+)$/, 1] - - # If there's no extension in the path, check request.format - if extension.nil? - extension = request.cache_format - end - extension + @extension = request.path[/^[^.]+\.(.+)$/, 1] || request.cache_format end end end diff --git a/actionpack/lib/action_controller/cgi/process.rb b/actionpack/lib/action_controller/cgi/process.rb index ffcad5666a..34b97776f5 100644 --- a/actionpack/lib/action_controller/cgi/process.rb +++ b/actionpack/lib/action_controller/cgi/process.rb @@ -45,6 +45,11 @@ module ActionController #:nodoc: out.sync = false if out.respond_to?(:sync=) headers['Status'] = status.to_s + + if headers.include?('Set-Cookie') + headers['cookie'] = headers.delete('Set-Cookie').split("\n") + end + out.write(cgi.header(headers)) body.each { |part| diff --git a/actionpack/lib/action_controller/dispatch/dispatcher.rb b/actionpack/lib/action_controller/dispatch/dispatcher.rb index e205245f13..74c72e1a8b 100644 --- a/actionpack/lib/action_controller/dispatch/dispatcher.rb +++ b/actionpack/lib/action_controller/dispatch/dispatcher.rb @@ -5,15 +5,14 @@ module ActionController class << self def define_dispatcher_callbacks(cache_classes) unless cache_classes - # Development mode callbacks - before_dispatch :reload_application - after_dispatch :cleanup_application + unless self.middleware.include?(Reloader) + self.middleware.insert_after(ActionDispatch::Failsafe, Reloader) + end ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false end if defined?(ActiveRecord) - after_dispatch :checkin_connections to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers } end @@ -42,6 +41,30 @@ module ActionController callback = ActiveSupport::Callbacks::Callback.new(:prepare_dispatch, block, :identifier => identifier) @prepare_dispatch_callbacks.replace_or_append!(callback) end + + def run_prepare_callbacks + if defined?(Rails) && Rails.logger + logger = Rails.logger + else + logger = Logger.new($stderr) + end + + new(logger).send :run_callbacks, :prepare_dispatch + end + + def reload_application + # Run prepare callbacks before every request in development mode + run_prepare_callbacks + + Routing::Routes.reload + end + + def cleanup_application + # Cleanup the application before processing the current request. + ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord) + ActiveSupport::Dependencies.clear + ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord) + end end cattr_accessor :middleware @@ -88,29 +111,8 @@ module ActionController dispatch end - def reload_application - # Run prepare callbacks before every request in development mode - run_callbacks :prepare_dispatch - - Routing::Routes.reload - end - - # Cleanup the application by clearing out loaded classes so they can - # be reloaded on the next request without restarting the server. - def cleanup_application - ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord) - ActiveSupport::Dependencies.clear - ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord) - end - 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/dispatch/middlewares.rb b/actionpack/lib/action_controller/dispatch/middlewares.rb index 3bf3dbebab..b62b4f84a1 100644 --- a/actionpack/lib/action_controller/dispatch/middlewares.rb +++ b/actionpack/lib/action_controller/dispatch/middlewares.rb @@ -4,18 +4,10 @@ use "Rack::Lock", :if => lambda { use "ActionDispatch::Failsafe" -["ActionDispatch::Session::CookieStore", - "ActionDispatch::Session::MemCacheStore", - "ActiveRecord::SessionStore"].each do |store| - use(store, ActionController::Base.session_options, - :if => lambda { - if session_store = ActionController::Base.session_store - session_store.name == store - end - } - ) -end +use lambda { ActionController::Base.session_store }, + lambda { ActionController::Base.session_options } use "ActionDispatch::RewindableInput" use "ActionDispatch::ParamsParser" use "Rack::MethodOverride" +use "Rack::Head" diff --git a/actionpack/lib/action_controller/dispatch/rescue.rb b/actionpack/lib/action_controller/dispatch/rescue.rb index df0a976204..ec9eff65a9 100644 --- a/actionpack/lib/action_controller/dispatch/rescue.rb +++ b/actionpack/lib/action_controller/dispatch/rescue.rb @@ -99,13 +99,19 @@ module ActionController #:nodoc: # Attempts to render a static error page based on the # <tt>status_code</tt> thrown, or just return headers if no such file - # exists. For example, if a 500 error is being handled Rails will first - # attempt to render the file at <tt>public/500.html</tt>. If the file - # doesn't exist, the body of the response will be left empty. + # exists. At first, it will try to render a localized static page. + # For example, if a 500 error is being handled Rails and locale is :da, + # it will first attempt to render the file at <tt>public/500.da.html</tt> + # then attempt to render <tt>public/500.html</tt>. If none of them exist, + # the body of the response will be left empty. def render_optional_error_file(status_code) status = interpret_status(status_code) - path = "#{Rails.public_path}/#{status.to_s[0,3]}.html" - if File.exist?(path) + locale_path = "#{Rails.public_path}/#{status[0,3]}.#{I18n.locale}.html" if I18n.locale + path = "#{Rails.public_path}/#{status[0,3]}.html" + + if locale_path && File.exist?(locale_path) + render :file => locale_path, :status => status, :content_type => Mime::HTML + elsif File.exist?(path) render :file => path, :status => status, :content_type => Mime::HTML else head status diff --git a/actionpack/lib/action_controller/reloader.rb b/actionpack/lib/action_controller/reloader.rb new file mode 100644 index 0000000000..46789309cd --- /dev/null +++ b/actionpack/lib/action_controller/reloader.rb @@ -0,0 +1,14 @@ +module ActionController + class Reloader + def initialize(app) + @app = app + end + + def call(env) + Dispatcher.reload_application + @app.call(env) + ensure + Dispatcher.cleanup_application + 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/generation/polymorphic_routes.rb b/actionpack/lib/action_controller/routing/generation/polymorphic_routes.rb index 924d1aa6bd..d9b614c237 100644 --- a/actionpack/lib/action_controller/routing/generation/polymorphic_routes.rb +++ b/actionpack/lib/action_controller/routing/generation/polymorphic_routes.rb @@ -163,7 +163,8 @@ module ActionController if parent.is_a?(Symbol) || parent.is_a?(String) string << "#{parent}_" else - string << "#{RecordIdentifier.__send__("singular_class_name", parent)}_" + string << "#{RecordIdentifier.__send__("plural_class_name", parent)}".singularize + string << "_" end end end @@ -171,7 +172,9 @@ module ActionController if record.is_a?(Symbol) || record.is_a?(String) route << "#{record}_" else - route << "#{RecordIdentifier.__send__("#{inflection}_class_name", record)}_" + route << "#{RecordIdentifier.__send__("plural_class_name", record)}" + route = route.singularize if inflection == :singular + route << "_" end action_prefix(options) + namespace + route + routing_type(options).to_s diff --git a/actionpack/lib/action_controller/routing/generation/url_rewriter.rb b/actionpack/lib/action_controller/routing/generation/url_rewriter.rb index bb6cb437b7..16720b915b 100644 --- a/actionpack/lib/action_controller/routing/generation/url_rewriter.rb +++ b/actionpack/lib/action_controller/routing/generation/url_rewriter.rb @@ -68,29 +68,17 @@ module ActionController # This generates, among other things, the method <tt>users_path</tt>. By default, # this method is accessible from your controllers, views and mailers. If you need # to access this auto-generated method from other places (such as a model), then - # you can do that in two ways. - # - # The first way is to include ActionController::UrlWriter in your class: + # you can do that by including ActionController::UrlWriter in your class: # # class User < ActiveRecord::Base - # include ActionController::UrlWriter # !!! + # include ActionController::UrlWriter # - # def name=(value) - # write_attribute('name', value) - # write_attribute('base_uri', users_path) # !!! + # def base_uri + # user_path(self) # end # end # - # The second way is to access them through ActionController::UrlWriter. - # The autogenerated named routes methods are available as class methods: - # - # class User < ActiveRecord::Base - # def name=(value) - # write_attribute('name', value) - # path = ActionController::UrlWriter.users_path # !!! - # write_attribute('base_uri', path) # !!! - # end - # end + # User.find(1).base_uri # => "/users/1" module UrlWriter def self.included(base) #:nodoc: ActionController::Routing::Routes.install_helpers(base) 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/resources.rb b/actionpack/lib/action_controller/routing/resources.rb index e8988aa737..86abb7b2f4 100644 --- a/actionpack/lib/action_controller/routing/resources.rb +++ b/actionpack/lib/action_controller/routing/resources.rb @@ -42,7 +42,7 @@ module ActionController # # Read more about REST at http://en.wikipedia.org/wiki/Representational_State_Transfer module Resources - INHERITABLE_OPTIONS = :namespace, :shallow, :actions + INHERITABLE_OPTIONS = :namespace, :shallow class Resource #:nodoc: DEFAULT_ACTIONS = :index, :create, :new, :edit, :show, :update, :destroy @@ -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 @@ -119,7 +119,7 @@ module ActionController end def has_action?(action) - !DEFAULT_ACTIONS.include?(action) || @options[:actions].nil? || @options[:actions].include?(action) + !DEFAULT_ACTIONS.include?(action) || action_allowed?(action) end protected @@ -135,24 +135,29 @@ module ActionController end def set_allowed_actions - only = @options.delete(:only) - except = @options.delete(:except) + only, except = @options.values_at(:only, :except) + @allowed_actions ||= {} - if only && except - raise ArgumentError, 'Please supply either :only or :except, not both.' - elsif only == :all || except == :none - options[:actions] = DEFAULT_ACTIONS + if only == :all || except == :none + only = nil + except = [] elsif only == :none || except == :all - options[:actions] = [] - elsif only - options[:actions] = DEFAULT_ACTIONS & Array(only).map(&:to_sym) + only = [] + except = nil + end + + if only + @allowed_actions[:only] = Array(only).map(&:to_sym) elsif except - options[:actions] = DEFAULT_ACTIONS - Array(except).map(&:to_sym) - else - # leave options[:actions] alone + @allowed_actions[:except] = Array(except).map(&:to_sym) end end + def action_allowed?(action) + only, except = @allowed_actions.values_at(:only, :except) + (!only || only.include?(action)) && (!except || !except.include?(action)) + end + def set_prefixes @path_prefix = options.delete(:path_prefix) @name_prefix = options.delete(:name_prefix) @@ -403,8 +408,6 @@ module ActionController # # --> POST /posts/1/comments (maps to the CommentsController#create action) # # --> PUT /posts/1/comments/1 (fails) # - # The <tt>:only</tt> and <tt>:except</tt> options are inherited by any nested resource(s). - # # If <tt>map.resources</tt> is called with multiple resources, they all get the same options applied. # # Examples: @@ -627,7 +630,7 @@ module ActionController action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash) action_path ||= Base.resources_path_names[action] || action - map_resource_routes(map, resource, action, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m) + map_resource_routes(map, resource, action, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m, { :force_id => true }) end end end @@ -638,9 +641,9 @@ module ActionController map_resource_routes(map, resource, :destroy, resource.member_path, route_path) end - def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil) + def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil, resource_options = {} ) if resource.has_action?(action) - action_options = action_options_for(action, resource, method) + action_options = action_options_for(action, resource, method, resource_options) formatted_route_path = "#{route_path}.:format" if route_name && @set.named_routes[route_name.to_sym].nil? @@ -657,9 +660,10 @@ module ActionController end end - def action_options_for(action, resource, method = nil) + def action_options_for(action, resource, method = nil, resource_options = {}) default_options = { :action => action.to_s } require_id = !resource.kind_of?(SingletonResource) + force_id = resource_options[:force_id] && !resource.kind_of?(SingletonResource) case default_options[:action] when "index", "new"; default_options.merge(add_conditions_for(resource.conditions, method || :get)).merge(resource.requirements) @@ -667,7 +671,7 @@ 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 default_options.merge(add_conditions_for(resource.conditions, method)).merge(resource.requirements(force_id)) end end end diff --git a/actionpack/lib/action_controller/routing/segments.rb b/actionpack/lib/action_controller/routing/segments.rb index 5dda3d4d00..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 @@ -191,23 +195,19 @@ module ActionController end def regexp_chunk - if regexp - if regexp_has_modifiers? - "(#{regexp.to_s})" - else - "(#{regexp.source})" - end - else - "([^#{Routing::SEPARATORS.join}]+)" - end + regexp ? regexp_string : default_regexp_chunk + end + + def regexp_string + regexp_has_modifiers? ? "(#{regexp.to_s})" : "(#{regexp.source})" + end + + def default_regexp_chunk + "([^#{Routing::SEPARATORS.join}]+)" end def number_of_captures - if regexp - regexp.number_of_captures + 1 - else - 1 - end + regexp ? regexp.number_of_captures + 1 : 1 end def build_pattern(pattern) @@ -244,10 +244,6 @@ module ActionController "(?i-:(#{(regexp || Regexp.union(*possible_names)).source}))" end - def number_of_captures - 1 - end - # Don't URI.escape the controller name since it may contain slashes. def interpolation_chunk(value_code = local_name) "\#{#{value_code}.to_s}" @@ -289,8 +285,8 @@ module ActionController "params[:#{key}] = PathSegment::Result.new_escaped((match[#{next_capture}]#{" || " + default.inspect if default}).split('/'))#{" if match[" + next_capture + "]" if !default}" end - def regexp_chunk - regexp || "(.*)" + def default_regexp_chunk + "(.*)" end def number_of_captures @@ -322,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/testing/integration.rb b/actionpack/lib/action_controller/testing/integration.rb index 0da23f9dc8..d51b9b63ff 100644 --- a/actionpack/lib/action_controller/testing/integration.rb +++ b/actionpack/lib/action_controller/testing/integration.rb @@ -5,7 +5,7 @@ require 'active_support/test_case' module ActionController module Integration #:nodoc: # An integration Session instance represents a set of requests and responses - # performed sequentially by some virtual user. Becase you can instantiate + # performed sequentially by some virtual user. Because you can instantiate # multiple sessions and run them side-by-side, you can also mimic (to some # limited extent) multiple simultaneous users interacting with your system. # @@ -26,6 +26,9 @@ module ActionController # The status message that accompanied the status code of the last request. attr_reader :status_message + # The body of the last request. + attr_reader :body + # The URI of the last request. attr_reader :path @@ -308,7 +311,11 @@ module ActionController ActionController::Base.clear_last_instantiation! - app = Rack::Lint.new(@application) + app = @application + # Rack::Lint doesn't accept String headers or bodies in Ruby 1.9 + unless RUBY_VERSION >= '1.9.0' && Rack.release <= '0.9.0' + app = Rack::Lint.new(app) + end status, headers, body = app.call(env) @request_count += 1 @@ -320,13 +327,19 @@ module ActionController @headers = Rack::Utils::HeaderHash.new(headers) - (@headers['Set-Cookie'] || []).each do |cookie| + (@headers['Set-Cookie'] || "").split("\n").each do |cookie| name, value = cookie.match(/^([^=]*)=([^;]*);/)[1,2] @cookies[name] = value end - @body = "" - body.each { |part| @body << part } + if body.is_a?(String) + @body_parts = [body] + @body = body + else + @body_parts = [] + body.each { |part| @body_parts << part.to_s } + @body = @body_parts.join + end if @controller = ActionController::Base.last_instantiation @request = @controller.request @@ -338,7 +351,7 @@ module ActionController @response = ActionDispatch::Response.new @response.status = status.to_s @response.headers.replace(@headers) - @response.body = @body + @response.body = @body_parts end # Decorate the response with the standard behavior of the diff --git a/actionpack/lib/action_controller/testing/process.rb b/actionpack/lib/action_controller/testing/process.rb index 38e37c7a18..86e193efa9 100644 --- a/actionpack/lib/action_controller/testing/process.rb +++ b/actionpack/lib/action_controller/testing/process.rb @@ -1,14 +1,21 @@ +require 'rack/session/abstract/id' module ActionController #:nodoc: class TestRequest < ActionDispatch::Request #:nodoc: attr_accessor :cookies, :session_options attr_accessor :query_parameters, :path, :session attr_accessor :host - def initialize - super(Rack::MockRequest.env_for("/")) + def self.new(env = {}) + super + end + + def initialize(env = {}) + super(Rack::MockRequest.env_for("/").merge(env)) @query_parameters = {} @session = TestSession.new + default_rack_options = Rack::Session::Abstract::ID::DEFAULT_OPTIONS + @session_options ||= {:id => generate_sid(default_rack_options[:sidbits])}.merge(default_rack_options) initialize_default_values initialize_containers @@ -106,6 +113,7 @@ module ActionController #:nodoc: end def recycle! + @env["action_controller.request.request_parameters"] = {} self.query_parameters = {} self.path_parameters = {} @headers, @request_method, @accepts, @content_type = nil, nil, nil, nil @@ -116,6 +124,10 @@ module ActionController #:nodoc: end private + def generate_sid(sidbits) + "%0#{sidbits / 4}x" % rand(2**sidbits - 1) + end + def initialize_containers @cookies = {} end @@ -246,7 +258,7 @@ module ActionController #:nodoc: def cookies cookies = {} Array(headers['Set-Cookie']).each do |cookie| - key, value = cookie.split(";").first.split("=") + key, value = cookie.split(";").first.split("=").map {|val| Rack::Utils.unescape(val)} cookies[key] = value end cookies @@ -254,11 +266,11 @@ module ActionController #:nodoc: # Returns binary content (downloadable file), converted to a String def binary_content - raise "Response body is not a Proc: #{body.inspect}" unless body.kind_of?(Proc) + raise "Response body is not a Proc: #{body_parts.inspect}" unless body_parts.kind_of?(Proc) require 'stringio' sio = StringIO.new - body.call(self, sio) + body_parts.call(self, sio) sio.rewind sio.read diff --git a/actionpack/lib/action_controller/testing/test_case.rb b/actionpack/lib/action_controller/testing/test_case.rb index 4f38f75f41..b020b755a0 100644 --- a/actionpack/lib/action_controller/testing/test_case.rb +++ b/actionpack/lib/action_controller/testing/test_case.rb @@ -127,9 +127,14 @@ module ActionController # # The exception is stored in the exception accessor for further inspection. module RaiseActionExceptions - protected - attr_accessor :exception + def self.included(base) + base.class_eval do + attr_accessor :exception + protected :exception, :exception= + end + end + protected def rescue_action_without_handler(e) self.exception = e @@ -141,9 +146,7 @@ module ActionController end end - def setup - setup_controller_request_and_response - end + setup :setup_controller_request_and_response @@controller_class = nil 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_controller/vendor/rack-1.0/rack.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack.rb new file mode 100644 index 0000000000..6349b95094 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack.rb @@ -0,0 +1,89 @@ +# Copyright (C) 2007, 2008, 2009 Christian Neukirchen <purl.org/net/chneukirchen> +# +# Rack is freely distributable under the terms of an MIT-style license. +# See COPYING or http://www.opensource.org/licenses/mit-license.php. + +$:.unshift(File.expand_path(File.dirname(__FILE__))) + + +# The Rack main module, serving as a namespace for all core Rack +# modules and classes. +# +# All modules meant for use in your application are <tt>autoload</tt>ed here, +# so it should be enough just to <tt>require rack.rb</tt> in your code. + +module Rack + # The Rack protocol version number implemented. + VERSION = [0,1] + + # Return the Rack protocol version as a dotted string. + def self.version + VERSION.join(".") + end + + # Return the Rack release as a dotted string. + def self.release + "1.0 bundled" + end + + autoload :Builder, "rack/builder" + autoload :Cascade, "rack/cascade" + autoload :Chunked, "rack/chunked" + autoload :CommonLogger, "rack/commonlogger" + autoload :ConditionalGet, "rack/conditionalget" + autoload :ContentLength, "rack/content_length" + autoload :ContentType, "rack/content_type" + autoload :File, "rack/file" + autoload :Deflater, "rack/deflater" + autoload :Directory, "rack/directory" + autoload :ForwardRequest, "rack/recursive" + autoload :Handler, "rack/handler" + autoload :Head, "rack/head" + autoload :Lint, "rack/lint" + autoload :Lock, "rack/lock" + autoload :MethodOverride, "rack/methodoverride" + autoload :Mime, "rack/mime" + autoload :Recursive, "rack/recursive" + autoload :Reloader, "rack/reloader" + autoload :ShowExceptions, "rack/showexceptions" + autoload :ShowStatus, "rack/showstatus" + autoload :Static, "rack/static" + autoload :URLMap, "rack/urlmap" + autoload :Utils, "rack/utils" + + autoload :MockRequest, "rack/mock" + autoload :MockResponse, "rack/mock" + + autoload :Request, "rack/request" + autoload :Response, "rack/response" + + module Auth + autoload :Basic, "rack/auth/basic" + autoload :AbstractRequest, "rack/auth/abstract/request" + autoload :AbstractHandler, "rack/auth/abstract/handler" + autoload :OpenID, "rack/auth/openid" + module Digest + autoload :MD5, "rack/auth/digest/md5" + autoload :Nonce, "rack/auth/digest/nonce" + autoload :Params, "rack/auth/digest/params" + autoload :Request, "rack/auth/digest/request" + end + end + + module Session + autoload :Cookie, "rack/session/cookie" + autoload :Pool, "rack/session/pool" + autoload :Memcache, "rack/session/memcache" + end + + # *Adapters* connect Rack with third party web frameworks. + # + # Rack includes an adapter for Camping, see README for other + # frameworks supporting Rack in their code bases. + # + # Refer to the submodules for framework-specific calling details. + + module Adapter + autoload :Camping, "rack/adapter/camping" + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/adapter/camping.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/adapter/camping.rb new file mode 100644 index 0000000000..63bc787f54 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/adapter/camping.rb @@ -0,0 +1,22 @@ +module Rack + module Adapter + class Camping + def initialize(app) + @app = app + end + + def call(env) + env["PATH_INFO"] ||= "" + env["SCRIPT_NAME"] ||= "" + controller = @app.run(env['rack.input'], env) + h = controller.headers + h.each_pair do |k,v| + if v.kind_of? URI + h[k] = v.to_s + end + end + [controller.status, controller.headers, [controller.body.to_s]] + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/handler.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/handler.rb new file mode 100644 index 0000000000..214df6299e --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/handler.rb @@ -0,0 +1,37 @@ +module Rack + module Auth + # Rack::Auth::AbstractHandler implements common authentication functionality. + # + # +realm+ should be set for all handlers. + + class AbstractHandler + + attr_accessor :realm + + def initialize(app, realm=nil, &authenticator) + @app, @realm, @authenticator = app, realm, authenticator + end + + + private + + def unauthorized(www_authenticate = challenge) + return [ 401, + { 'Content-Type' => 'text/plain', + 'Content-Length' => '0', + 'WWW-Authenticate' => www_authenticate.to_s }, + [] + ] + end + + def bad_request + return [ 400, + { 'Content-Type' => 'text/plain', + 'Content-Length' => '0' }, + [] + ] + end + + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/request.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/request.rb new file mode 100644 index 0000000000..1d9ccec685 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/abstract/request.rb @@ -0,0 +1,37 @@ +module Rack + module Auth + class AbstractRequest + + def initialize(env) + @env = env + end + + def provided? + !authorization_key.nil? + end + + def parts + @parts ||= @env[authorization_key].split(' ', 2) + end + + def scheme + @scheme ||= parts.first.downcase.to_sym + end + + def params + @params ||= parts.last + end + + + private + + AUTHORIZATION_KEYS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION'] + + def authorization_key + @authorization_key ||= AUTHORIZATION_KEYS.detect { |key| @env.has_key?(key) } + end + + end + + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/basic.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/basic.rb new file mode 100644 index 0000000000..9557224648 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/basic.rb @@ -0,0 +1,58 @@ +require 'rack/auth/abstract/handler' +require 'rack/auth/abstract/request' + +module Rack + module Auth + # Rack::Auth::Basic implements HTTP Basic Authentication, as per RFC 2617. + # + # Initialize with the Rack application that you want protecting, + # and a block that checks if a username and password pair are valid. + # + # See also: <tt>example/protectedlobster.rb</tt> + + class Basic < AbstractHandler + + def call(env) + auth = Basic::Request.new(env) + + return unauthorized unless auth.provided? + + return bad_request unless auth.basic? + + if valid?(auth) + env['REMOTE_USER'] = auth.username + + return @app.call(env) + end + + unauthorized + end + + + private + + def challenge + 'Basic realm="%s"' % realm + end + + def valid?(auth) + @authenticator.call(*auth.credentials) + end + + class Request < Auth::AbstractRequest + def basic? + :basic == scheme + end + + def credentials + @credentials ||= params.unpack("m*").first.split(/:/, 2) + end + + def username + credentials.first + end + end + + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/md5.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/md5.rb new file mode 100644 index 0000000000..e579dc9632 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/md5.rb @@ -0,0 +1,124 @@ +require 'rack/auth/abstract/handler' +require 'rack/auth/digest/request' +require 'rack/auth/digest/params' +require 'rack/auth/digest/nonce' +require 'digest/md5' + +module Rack + module Auth + module Digest + # Rack::Auth::Digest::MD5 implements the MD5 algorithm version of + # HTTP Digest Authentication, as per RFC 2617. + # + # Initialize with the [Rack] application that you want protecting, + # and a block that looks up a plaintext password for a given username. + # + # +opaque+ needs to be set to a constant base64/hexadecimal string. + # + class MD5 < AbstractHandler + + attr_accessor :opaque + + attr_writer :passwords_hashed + + def initialize(*args) + super + @passwords_hashed = nil + end + + def passwords_hashed? + !!@passwords_hashed + end + + def call(env) + auth = Request.new(env) + + unless auth.provided? + return unauthorized + end + + if !auth.digest? || !auth.correct_uri? || !valid_qop?(auth) + return bad_request + end + + if valid?(auth) + if auth.nonce.stale? + return unauthorized(challenge(:stale => true)) + else + env['REMOTE_USER'] = auth.username + + return @app.call(env) + end + end + + unauthorized + end + + + private + + QOP = 'auth'.freeze + + def params(hash = {}) + Params.new do |params| + params['realm'] = realm + params['nonce'] = Nonce.new.to_s + params['opaque'] = H(opaque) + params['qop'] = QOP + + hash.each { |k, v| params[k] = v } + end + end + + def challenge(hash = {}) + "Digest #{params(hash)}" + end + + def valid?(auth) + valid_opaque?(auth) && valid_nonce?(auth) && valid_digest?(auth) + end + + def valid_qop?(auth) + QOP == auth.qop + end + + def valid_opaque?(auth) + H(opaque) == auth.opaque + end + + def valid_nonce?(auth) + auth.nonce.valid? + end + + def valid_digest?(auth) + digest(auth, @authenticator.call(auth.username)) == auth.response + end + + def md5(data) + ::Digest::MD5.hexdigest(data) + end + + alias :H :md5 + + def KD(secret, data) + H([secret, data] * ':') + end + + def A1(auth, password) + [ auth.username, auth.realm, password ] * ':' + end + + def A2(auth) + [ auth.method, auth.uri ] * ':' + end + + def digest(auth, password) + password_hash = passwords_hashed? ? password : H(A1(auth, password)) + + KD(password_hash, [ auth.nonce, auth.nc, auth.cnonce, QOP, H(A2(auth)) ] * ':') + end + + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/nonce.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/nonce.rb new file mode 100644 index 0000000000..dbe109f29a --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/nonce.rb @@ -0,0 +1,51 @@ +require 'digest/md5' + +module Rack + module Auth + module Digest + # Rack::Auth::Digest::Nonce is the default nonce generator for the + # Rack::Auth::Digest::MD5 authentication handler. + # + # +private_key+ needs to set to a constant string. + # + # +time_limit+ can be optionally set to an integer (number of seconds), + # to limit the validity of the generated nonces. + + class Nonce + + class << self + attr_accessor :private_key, :time_limit + end + + def self.parse(string) + new(*string.unpack("m*").first.split(' ', 2)) + end + + def initialize(timestamp = Time.now, given_digest = nil) + @timestamp, @given_digest = timestamp.to_i, given_digest + end + + def to_s + [([ @timestamp, digest ] * ' ')].pack("m*").strip + end + + def digest + ::Digest::MD5.hexdigest([ @timestamp, self.class.private_key ] * ':') + end + + def valid? + digest == @given_digest + end + + def stale? + !self.class.time_limit.nil? && (@timestamp - Time.now.to_i) < self.class.time_limit + end + + def fresh? + !stale? + end + + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/params.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/params.rb new file mode 100644 index 0000000000..730e2efdc8 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/params.rb @@ -0,0 +1,55 @@ +module Rack + module Auth + module Digest + class Params < Hash + + def self.parse(str) + split_header_value(str).inject(new) do |header, param| + k, v = param.split('=', 2) + header[k] = dequote(v) + header + end + end + + def self.dequote(str) # From WEBrick::HTTPUtils + ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup + ret.gsub!(/\\(.)/, "\\1") + ret + end + + def self.split_header_value(str) + str.scan( /(\w+\=(?:"[^\"]+"|[^,]+))/n ).collect{ |v| v[0] } + end + + def initialize + super + + yield self if block_given? + end + + def [](k) + super k.to_s + end + + def []=(k, v) + super k.to_s, v.to_s + end + + UNQUOTED = ['qop', 'nc', 'stale'] + + def to_s + inject([]) do |parts, (k, v)| + parts << "#{k}=" + (UNQUOTED.include?(k) ? v.to_s : quote(v)) + parts + end.join(', ') + end + + def quote(str) # From WEBrick::HTTPUtils + '"' << str.gsub(/[\\\"]/o, "\\\1") << '"' + end + + end + end + end +end + diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/request.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/request.rb new file mode 100644 index 0000000000..a8aa3bf996 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/digest/request.rb @@ -0,0 +1,40 @@ +require 'rack/auth/abstract/request' +require 'rack/auth/digest/params' +require 'rack/auth/digest/nonce' + +module Rack + module Auth + module Digest + class Request < Auth::AbstractRequest + + def method + @env['rack.methodoverride.original_method'] || @env['REQUEST_METHOD'] + end + + def digest? + :digest == scheme + end + + def correct_uri? + (@env['SCRIPT_NAME'].to_s + @env['PATH_INFO'].to_s) == uri + end + + def nonce + @nonce ||= Nonce.parse(params['nonce']) + end + + def params + @params ||= Params.parse(parts.last) + end + + def method_missing(sym) + if params.has_key? key = sym.to_s + return params[key] + end + super + end + + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/openid.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/openid.rb new file mode 100644 index 0000000000..c5f6a5143e --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/auth/openid.rb @@ -0,0 +1,480 @@ +# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net + +gem 'ruby-openid', '~> 2' if defined? Gem +require 'rack/request' +require 'rack/utils' +require 'rack/auth/abstract/handler' +require 'uri' +require 'openid' #gem +require 'openid/extension' #gem +require 'openid/store/memory' #gem + +module Rack + class Request + def openid_request + @env['rack.auth.openid.request'] + end + + def openid_response + @env['rack.auth.openid.response'] + end + end + + module Auth + + # Rack::Auth::OpenID provides a simple method for setting up an OpenID + # Consumer. It requires the ruby-openid library from janrain to operate, + # as well as a rack method of session management. + # + # The ruby-openid home page is at http://openidenabled.com/ruby-openid/. + # + # The OpenID specifications can be found at + # http://openid.net/specs/openid-authentication-1_1.html + # and + # http://openid.net/specs/openid-authentication-2_0.html. Documentation + # for published OpenID extensions and related topics can be found at + # http://openid.net/developers/specs/. + # + # It is recommended to read through the OpenID spec, as well as + # ruby-openid's documentation, to understand what exactly goes on. However + # a setup as simple as the presented examples is enough to provide + # Consumer functionality. + # + # This library strongly intends to utilize the OpenID 2.0 features of the + # ruby-openid library, which provides OpenID 1.0 compatiblity. + # + # NOTE: Due to the amount of data that this library stores in the + # session, Rack::Session::Cookie may fault. + + class OpenID + + class NoSession < RuntimeError; end + class BadExtension < RuntimeError; end + # Required for ruby-openid + ValidStatus = [:success, :setup_needed, :cancel, :failure] + + # = Arguments + # + # The first argument is the realm, identifying the site they are trusting + # with their identity. This is required, also treated as the trust_root + # in OpenID 1.x exchanges. + # + # The optional second argument is a hash of options. + # + # == Options + # + # <tt>:return_to</tt> defines the url to return to after the client + # authenticates with the openid service provider. This url should point + # to where Rack::Auth::OpenID is mounted. If <tt>:return_to</tt> is not + # provided, return_to will be the current url which allows flexibility + # with caveats. + # + # <tt>:session_key</tt> defines the key to the session hash in the env. + # It defaults to 'rack.session'. + # + # <tt>:openid_param</tt> defines at what key in the request parameters to + # find the identifier to resolve. As per the 2.0 spec, the default is + # 'openid_identifier'. + # + # <tt>:store</tt> defined what OpenID Store to use for persistant + # information. By default a Store::Memory will be used. + # + # <tt>:immediate</tt> as true will make initial requests to be of an + # immediate type. This is false by default. See OpenID specification + # documentation. + # + # <tt>:extensions</tt> should be a hash of openid extension + # implementations. The key should be the extension main module, the value + # should be an array of arguments for extension::Request.new. + # The hash is iterated over and passed to #add_extension for processing. + # Please see #add_extension for further documentation. + # + # == Examples + # + # simple_oid = OpenID.new('http://mysite.com/') + # + # return_oid = OpenID.new('http://mysite.com/', { + # :return_to => 'http://mysite.com/openid' + # }) + # + # complex_oid = OpenID.new('http://mysite.com/', + # :immediate => true, + # :extensions => { + # ::OpenID::SReg => [['email'],['nickname']] + # } + # ) + # + # = Advanced + # + # Most of the functionality of this library is encapsulated such that + # expansion and overriding functions isn't difficult nor tricky. + # Alternately, to avoid opening up singleton objects or subclassing, a + # wrapper rack middleware can be composed to act upon Auth::OpenID's + # responses. See #check and #finish for locations of pertinent data. + # + # == Responses + # + # To change the responses that Auth::OpenID returns, override the methods + # #redirect, #bad_request, #unauthorized, #access_denied, and + # #foreign_server_failure. + # + # Additionally #confirm_post_params is used when the URI would exceed + # length limits on a GET request when doing the initial verification + # request. + # + # == Processing + # + # To change methods of processing completed transactions, override the + # methods #success, #setup_needed, #cancel, and #failure. Please ensure + # the returned object is a rack compatible response. + # + # The first argument is an OpenID::Response, the second is a + # Rack::Request of the current request, the last is the hash used in + # ruby-openid handling, which can be found manually at + # env['rack.session'][:openid]. + # + # This is useful if you wanted to expand the processing done, such as + # setting up user accounts. + # + # oid_app = Rack::Auth::OpenID.new realm, :return_to => return_to + # def oid_app.success oid, request, session + # user = Models::User[oid.identity_url] + # user ||= Models::User.create_from_openid oid + # request['rack.session'][:user] = user.id + # redirect MyApp.site_home + # end + # + # site_map['/openid'] = oid_app + # map = Rack::URLMap.new site_map + # ... + + def initialize(realm, options={}) + realm = URI(realm) + raise ArgumentError, "Invalid realm: #{realm}" \ + unless realm.absolute? \ + and realm.fragment.nil? \ + and realm.scheme =~ /^https?$/ \ + and realm.host =~ /^(\*\.)?#{URI::REGEXP::PATTERN::URIC_NO_SLASH}+/ + realm.path = '/' if realm.path.empty? + @realm = realm.to_s + + if ruri = options[:return_to] + ruri = URI(ruri) + raise ArgumentError, "Invalid return_to: #{ruri}" \ + unless ruri.absolute? \ + and ruri.scheme =~ /^https?$/ \ + and ruri.fragment.nil? + raise ArgumentError, "return_to #{ruri} not within realm #{realm}" \ + unless self.within_realm?(ruri) + @return_to = ruri.to_s + end + + @session_key = options[:session_key] || 'rack.session' + @openid_param = options[:openid_param] || 'openid_identifier' + @store = options[:store] || ::OpenID::Store::Memory.new + @immediate = !!options[:immediate] + + @extensions = {} + if extensions = options.delete(:extensions) + extensions.each do |ext, args| + add_extension ext, *args + end + end + + # Undocumented, semi-experimental + @anonymous = !!options[:anonymous] + end + + attr_reader :realm, :return_to, :session_key, :openid_param, :store, + :immediate, :extensions + + # Sets up and uses session data at <tt>:openid</tt> within the session. + # Errors in this setup will raise a NoSession exception. + # + # If the parameter 'openid.mode' is set, which implies a followup from + # the openid server, processing is passed to #finish and the result is + # returned. However, if there is no appropriate openid information in the + # session, a 400 error is returned. + # + # If the parameter specified by <tt>options[:openid_param]</tt> is + # present, processing is passed to #check and the result is returned. + # + # If neither of these conditions are met, #unauthorized is called. + + def call(env) + env['rack.auth.openid'] = self + env_session = env[@session_key] + unless env_session and env_session.is_a?(Hash) + raise NoSession, 'No compatible session' + end + # let us work in our own namespace... + session = (env_session[:openid] ||= {}) + unless session and session.is_a?(Hash) + raise NoSession, 'Incompatible openid session' + end + + request = Rack::Request.new(env) + consumer = ::OpenID::Consumer.new(session, @store) + + if mode = request.GET['openid.mode'] + if session.key?(:openid_param) + finish(consumer, session, request) + else + bad_request + end + elsif request.GET[@openid_param] + check(consumer, session, request) + else + unauthorized + end + end + + # As the first part of OpenID consumer action, #check retrieves the data + # required for completion. + # + # If all parameters fit within the max length of a URI, a 303 redirect + # will be returned. Otherwise #confirm_post_params will be called. + # + # Any messages from OpenID's request are logged to env['rack.errors'] + # + # <tt>env['rack.auth.openid.request']</tt> is the openid checkid request + # instance. + # + # <tt>session[:openid_param]</tt> is set to the openid identifier + # provided by the user. + # + # <tt>session[:return_to]</tt> is set to the return_to uri given to the + # identity provider. + + def check(consumer, session, req) + oid = consumer.begin(req.GET[@openid_param], @anonymous) + req.env['rack.auth.openid.request'] = oid + req.env['rack.errors'].puts(oid.message) + p oid if $DEBUG + + ## Extension support + extensions.each do |ext,args| + oid.add_extension(ext::Request.new(*args)) + end + + session[:openid_param] = req.GET[openid_param] + return_to_uri = return_to ? return_to : req.url + session[:return_to] = return_to_uri + immediate = session.key?(:setup_needed) ? false : immediate + + if oid.send_redirect?(realm, return_to_uri, immediate) + uri = oid.redirect_url(realm, return_to_uri, immediate) + redirect(uri) + else + confirm_post_params(oid, realm, return_to_uri, immediate) + end + rescue ::OpenID::DiscoveryFailure => e + # thrown from inside OpenID::Consumer#begin by yadis stuff + req.env['rack.errors'].puts([e.message, *e.backtrace]*"\n") + return foreign_server_failure + end + + # This is the final portion of authentication. + # If successful, a redirect to the realm is be returned. + # Data gathered from extensions are stored in session[:openid] with the + # extension's namespace uri as the key. + # + # Any messages from OpenID's response are logged to env['rack.errors'] + # + # <tt>env['rack.auth.openid.response']</tt> will contain the openid + # response. + + def finish(consumer, session, req) + oid = consumer.complete(req.GET, req.url) + req.env['rack.auth.openid.response'] = oid + req.env['rack.errors'].puts(oid.message) + p oid if $DEBUG + + raise unless ValidStatus.include?(oid.status) + __send__(oid.status, oid, req, session) + end + + # The first argument should be the main extension module. + # The extension module should contain the constants: + # * class Request, should have OpenID::Extension as an ancestor + # * class Response, should have OpenID::Extension as an ancestor + # * string NS_URI, which defining the namespace of the extension + # + # All trailing arguments will be passed to extension::Request.new in + # #check. + # The openid response will be passed to + # extension::Response#from_success_response, #get_extension_args will be + # called on the result to attain the gathered data. + # + # This method returns the key at which the response data will be found in + # the session, which is the namespace uri by default. + + def add_extension(ext, *args) + raise BadExtension unless valid_extension?(ext) + extensions[ext] = args + return ext::NS_URI + end + + # Checks the validitity, in the context of usage, of a submitted + # extension. + + def valid_extension?(ext) + if not %w[NS_URI Request Response].all?{|c| ext.const_defined?(c) } + raise ArgumentError, 'Extension is missing constants.' + elsif not ext::Response.respond_to?(:from_success_response) + raise ArgumentError, 'Response is missing required method.' + end + return true + rescue + return false + end + + # Checks the provided uri to ensure it'd be considered within the realm. + # is currently not compatible with wildcard realms. + + def within_realm? uri + uri = URI.parse(uri.to_s) + realm = URI.parse(self.realm) + return false unless uri.absolute? + return false unless uri.path[0, realm.path.size] == realm.path + return false unless uri.host == realm.host or realm.host[/^\*\./] + # for wildcard support, is awkward with URI limitations + realm_match = Regexp.escape(realm.host). + sub(/^\*\./,"^#{URI::REGEXP::PATTERN::URIC_NO_SLASH}+.")+'$' + return false unless uri.host.match(realm_match) + return true + end + alias_method :include?, :within_realm? + + protected + + ### These methods define some of the boilerplate responses. + + # Returns an html form page for posting to an Identity Provider if the + # GET request would exceed the upper URI length limit. + + def confirm_post_params(oid, realm, return_to, immediate) + Rack::Response.new.finish do |r| + r.write '<html><head><title>Confirm...</title></head><body>' + r.write oid.form_markup(realm, return_to, immediate) + r.write '</body></html>' + end + end + + # Returns a 303 redirect with the destination of that provided by the + # argument. + + def redirect(uri) + [ 303, {'Content-Length'=>'0', 'Content-Type'=>'text/plain', + 'Location' => uri}, + [] ] + end + + # Returns an empty 400 response. + + def bad_request + [ 400, {'Content-Type'=>'text/plain', 'Content-Length'=>'0'}, + [''] ] + end + + # Returns a basic unauthorized 401 response. + + def unauthorized + [ 401, {'Content-Type' => 'text/plain', 'Content-Length' => '13'}, + ['Unauthorized.'] ] + end + + # Returns a basic access denied 403 response. + + def access_denied + [ 403, {'Content-Type' => 'text/plain', 'Content-Length' => '14'}, + ['Access denied.'] ] + end + + # Returns a 503 response to be used if communication with the remote + # OpenID server fails. + + def foreign_server_failure + [ 503, {'Content-Type'=>'text/plain', 'Content-Length' => '23'}, + ['Foreign server failure.'] ] + end + + private + + ### These methods are called after a transaction is completed, depending + # on its outcome. These should all return a rack compatible response. + # You'd want to override these to provide additional functionality. + + # Called to complete processing on a successful transaction. + # Within the openid session, :openid_identity and :openid_identifier are + # set to the user friendly and the standard representation of the + # validated identity. All other data in the openid session is cleared. + + def success(oid, request, session) + session.clear + session[:openid_identity] = oid.display_identifier + session[:openid_identifier] = oid.identity_url + extensions.keys.each do |ext| + label = ext.name[/[^:]+$/].downcase + response = ext::Response.from_success_response(oid) + session[label] = response.data + end + redirect(realm) + end + + # Called if the Identity Provider indicates further setup by the user is + # required. + # The identifier is retrived from the openid session at :openid_param. + # And :setup_needed is set to true to prevent looping. + + def setup_needed(oid, request, session) + identifier = session[:openid_param] + session[:setup_needed] = true + redirect req.script_name + '?' + openid_param + '=' + identifier + end + + # Called if the user indicates they wish to cancel identification. + # Data within openid session is cleared. + + def cancel(oid, request, session) + session.clear + access_denied + end + + # Called if the Identity Provider indicates the user is unable to confirm + # their identity. Data within the openid session is left alone, in case + # of swarm auth attacks. + + def failure(oid, request, session) + unauthorized + end + end + + # A class developed out of the request to use OpenID as an authentication + # middleware. The request will be sent to the OpenID instance unless the + # block evaluates to true. For example in rackup, you can use it as such: + # + # use Rack::Session::Pool + # use Rack::Auth::OpenIDAuth, realm, openid_options do |env| + # env['rack.session'][:authkey] == a_string + # end + # run RackApp + # + # Or simply: + # + # app = Rack::Auth::OpenIDAuth.new app, realm, openid_options, &auth + + class OpenIDAuth < Rack::Auth::AbstractHandler + attr_reader :oid + def initialize(app, realm, options={}, &auth) + @oid = OpenID.new(realm, options) + super(app, &auth) + end + + def call(env) + to = auth.call(env) ? @app : @oid + to.call env + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/builder.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/builder.rb new file mode 100644 index 0000000000..295235e56a --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/builder.rb @@ -0,0 +1,63 @@ +module Rack + # Rack::Builder implements a small DSL to iteratively construct Rack + # applications. + # + # Example: + # + # app = Rack::Builder.new { + # use Rack::CommonLogger + # use Rack::ShowExceptions + # map "/lobster" do + # use Rack::Lint + # run Rack::Lobster.new + # end + # } + # + # Or + # + # app = Rack::Builder.app do + # use Rack::CommonLogger + # lambda { |env| [200, {'Content-Type' => 'text/plain'}, 'OK'] } + # end + # + # +use+ adds a middleware to the stack, +run+ dispatches to an application. + # You can use +map+ to construct a Rack::URLMap in a convenient way. + + class Builder + def initialize(&block) + @ins = [] + instance_eval(&block) if block_given? + end + + def self.app(&block) + self.new(&block).to_app + end + + def use(middleware, *args, &block) + @ins << lambda { |app| middleware.new(app, *args, &block) } + end + + def run(app) + @ins << app #lambda { |nothing| app } + end + + def map(path, &block) + if @ins.last.kind_of? Hash + @ins.last[path] = self.class.new(&block).to_app + else + @ins << {} + map(path, &block) + end + end + + def to_app + @ins[-1] = Rack::URLMap.new(@ins.last) if Hash === @ins.last + inner_app = @ins.last + @ins[0...-1].reverse.inject(inner_app) { |a, e| e.call(a) } + end + + def call(env) + to_app.call(env) + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/cascade.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/cascade.rb new file mode 100644 index 0000000000..a038aa1105 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/cascade.rb @@ -0,0 +1,36 @@ +module Rack + # Rack::Cascade tries an request on several apps, and returns the + # first response that is not 404 (or in a list of configurable + # status codes). + + class Cascade + attr_reader :apps + + def initialize(apps, catch=404) + @apps = apps + @catch = [*catch] + end + + def call(env) + status = headers = body = nil + raise ArgumentError, "empty cascade" if @apps.empty? + @apps.each { |app| + begin + status, headers, body = app.call(env) + break unless @catch.include?(status.to_i) + end + } + [status, headers, body] + end + + def add app + @apps << app + end + + def include? app + @apps.include? app + end + + alias_method :<<, :add + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/chunked.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/chunked.rb new file mode 100644 index 0000000000..280d89dd65 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/chunked.rb @@ -0,0 +1,49 @@ +require 'rack/utils' + +module Rack + + # Middleware that applies chunked transfer encoding to response bodies + # when the response does not include a Content-Length header. + class Chunked + include Rack::Utils + + def initialize(app) + @app = app + end + + def call(env) + status, headers, body = @app.call(env) + headers = HeaderHash.new(headers) + + if env['HTTP_VERSION'] == 'HTTP/1.0' || + STATUS_WITH_NO_ENTITY_BODY.include?(status) || + headers['Content-Length'] || + headers['Transfer-Encoding'] + [status, headers.to_hash, body] + else + dup.chunk(status, headers, body) + end + end + + def chunk(status, headers, body) + @body = body + headers.delete('Content-Length') + headers['Transfer-Encoding'] = 'chunked' + [status, headers.to_hash, self] + end + + def each + term = "\r\n" + @body.each do |chunk| + size = bytesize(chunk) + next if size == 0 + yield [size.to_s(16), term, chunk, term].join + end + yield ["0", term, "", term].join + end + + def close + @body.close if @body.respond_to?(:close) + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/commonlogger.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/commonlogger.rb new file mode 100644 index 0000000000..5e68ac626d --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/commonlogger.rb @@ -0,0 +1,61 @@ +module Rack + # Rack::CommonLogger forwards every request to an +app+ given, and + # logs a line in the Apache common log format to the +logger+, or + # rack.errors by default. + + class CommonLogger + def initialize(app, logger=nil) + @app = app + @logger = logger + end + + def call(env) + dup._call(env) + end + + def _call(env) + @env = env + @logger ||= self + @time = Time.now + @status, @header, @body = @app.call(env) + [@status, @header, self] + end + + def close + @body.close if @body.respond_to? :close + end + + # By default, log to rack.errors. + def <<(str) + @env["rack.errors"].write(str) + @env["rack.errors"].flush + end + + def each + length = 0 + @body.each { |part| + length += part.size + yield part + } + + @now = Time.now + + # Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common + # lilith.local - - [07/Aug/2006 23:58:02] "GET / HTTP/1.1" 500 - + # %{%s - %s [%s] "%s %s%s %s" %d %s\n} % + @logger << %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f\n} % + [ + @env['HTTP_X_FORWARDED_FOR'] || @env["REMOTE_ADDR"] || "-", + @env["REMOTE_USER"] || "-", + @now.strftime("%d/%b/%Y %H:%M:%S"), + @env["REQUEST_METHOD"], + @env["PATH_INFO"], + @env["QUERY_STRING"].empty? ? "" : "?"+@env["QUERY_STRING"], + @env["HTTP_VERSION"], + @status.to_s[0..3], + (length.zero? ? "-" : length.to_s), + @now - @time + ] + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/conditionalget.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/conditionalget.rb new file mode 100644 index 0000000000..7bec824181 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/conditionalget.rb @@ -0,0 +1,45 @@ +require 'rack/utils' + +module Rack + + # Middleware that enables conditional GET using If-None-Match and + # If-Modified-Since. The application should set either or both of the + # Last-Modified or Etag response headers according to RFC 2616. When + # either of the conditions is met, the response body is set to be zero + # length and the response status is set to 304 Not Modified. + # + # Applications that defer response body generation until the body's each + # message is received will avoid response body generation completely when + # a conditional GET matches. + # + # Adapted from Michael Klishin's Merb implementation: + # http://github.com/wycats/merb-core/tree/master/lib/merb-core/rack/middleware/conditional_get.rb + class ConditionalGet + def initialize(app) + @app = app + end + + def call(env) + return @app.call(env) unless %w[GET HEAD].include?(env['REQUEST_METHOD']) + + status, headers, body = @app.call(env) + headers = Utils::HeaderHash.new(headers) + if etag_matches?(env, headers) || modified_since?(env, headers) + status = 304 + body = [] + end + [status, headers, body] + end + + private + def etag_matches?(env, headers) + etag = headers['Etag'] and etag == env['HTTP_IF_NONE_MATCH'] + end + + def modified_since?(env, headers) + last_modified = headers['Last-Modified'] and + last_modified == env['HTTP_IF_MODIFIED_SINCE'] + end + end + +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_length.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_length.rb new file mode 100644 index 0000000000..1e56d43853 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_length.rb @@ -0,0 +1,29 @@ +require 'rack/utils' + +module Rack + # Sets the Content-Length header on responses with fixed-length bodies. + class ContentLength + include Rack::Utils + + def initialize(app) + @app = app + end + + def call(env) + status, headers, body = @app.call(env) + headers = HeaderHash.new(headers) + + if !STATUS_WITH_NO_ENTITY_BODY.include?(status) && + !headers['Content-Length'] && + !headers['Transfer-Encoding'] && + (body.respond_to?(:to_ary) || body.respond_to?(:to_str)) + + body = [body] if body.respond_to?(:to_str) # rack 0.4 compat + length = body.to_ary.inject(0) { |len, part| len + bytesize(part) } + headers['Content-Length'] = length.to_s + end + + [status, headers, body] + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_type.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_type.rb new file mode 100644 index 0000000000..0c1e1ca3e1 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/content_type.rb @@ -0,0 +1,23 @@ +require 'rack/utils' + +module Rack + + # Sets the Content-Type header on responses which don't have one. + # + # Builder Usage: + # use Rack::ContentType, "text/plain" + # + # When no content type argument is provided, "text/html" is assumed. + class ContentType + def initialize(app, content_type = "text/html") + @app, @content_type = app, content_type + end + + def call(env) + status, headers, body = @app.call(env) + headers = Utils::HeaderHash.new(headers) + headers['Content-Type'] ||= @content_type + [status, headers.to_hash, body] + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/deflater.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/deflater.rb new file mode 100644 index 0000000000..a42b7477ae --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/deflater.rb @@ -0,0 +1,85 @@ +require "zlib" +require "stringio" +require "time" # for Time.httpdate +require 'rack/utils' + +module Rack + class Deflater + def initialize(app) + @app = app + end + + def call(env) + status, headers, body = @app.call(env) + headers = Utils::HeaderHash.new(headers) + + # Skip compressing empty entity body responses and responses with + # no-transform set. + if Utils::STATUS_WITH_NO_ENTITY_BODY.include?(status) || + headers['Cache-Control'].to_s =~ /\bno-transform\b/ + return [status, headers, body] + end + + request = Request.new(env) + + encoding = Utils.select_best_encoding(%w(gzip deflate identity), + request.accept_encoding) + + # Set the Vary HTTP header. + vary = headers["Vary"].to_s.split(",").map { |v| v.strip } + unless vary.include?("*") || vary.include?("Accept-Encoding") + headers["Vary"] = vary.push("Accept-Encoding").join(",") + end + + case encoding + when "gzip" + mtime = headers.key?("Last-Modified") ? + Time.httpdate(headers["Last-Modified"]) : Time.now + body = self.class.gzip(body, mtime) + size = Rack::Utils.bytesize(body) + headers = headers.merge("Content-Encoding" => "gzip", "Content-Length" => size.to_s) + [status, headers, [body]] + when "deflate" + body = self.class.deflate(body) + size = Rack::Utils.bytesize(body) + headers = headers.merge("Content-Encoding" => "deflate", "Content-Length" => size.to_s) + [status, headers, [body]] + when "identity" + [status, headers, body] + when nil + message = "An acceptable encoding for the requested resource #{request.fullpath} could not be found." + [406, {"Content-Type" => "text/plain", "Content-Length" => message.length.to_s}, [message]] + end + end + + def self.gzip(body, mtime) + io = StringIO.new + gzip = Zlib::GzipWriter.new(io) + gzip.mtime = mtime + + # TODO: Add streaming + body.each { |part| gzip << part } + + gzip.close + return io.string + end + + DEFLATE_ARGS = [ + Zlib::DEFAULT_COMPRESSION, + # drop the zlib header which causes both Safari and IE to choke + -Zlib::MAX_WBITS, + Zlib::DEF_MEM_LEVEL, + Zlib::DEFAULT_STRATEGY + ] + + # Loosely based on Mongrel's Deflate handler + def self.deflate(body) + deflater = Zlib::Deflate.new(*DEFLATE_ARGS) + + # TODO: Add streaming + body.each { |part| deflater << part } + + return deflater.finish + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/directory.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/directory.rb new file mode 100644 index 0000000000..acdd3029d3 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/directory.rb @@ -0,0 +1,153 @@ +require 'time' +require 'rack/utils' +require 'rack/mime' + +module Rack + # Rack::Directory serves entries below the +root+ given, according to the + # path info of the Rack request. If a directory is found, the file's contents + # will be presented in an html based index. If a file is found, the env will + # be passed to the specified +app+. + # + # If +app+ is not specified, a Rack::File of the same +root+ will be used. + + class Directory + DIR_FILE = "<tr><td class='name'><a href='%s'>%s</a></td><td class='size'>%s</td><td class='type'>%s</td><td class='mtime'>%s</td></tr>" + DIR_PAGE = <<-PAGE +<html><head> + <title>%s</title> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <style type='text/css'> +table { width:100%%; } +.name { text-align:left; } +.size, .mtime { text-align:right; } +.type { width:11em; } +.mtime { width:15em; } + </style> +</head><body> +<h1>%s</h1> +<hr /> +<table> + <tr> + <th class='name'>Name</th> + <th class='size'>Size</th> + <th class='type'>Type</th> + <th class='mtime'>Last Modified</th> + </tr> +%s +</table> +<hr /> +</body></html> + PAGE + + attr_reader :files + attr_accessor :root, :path + + def initialize(root, app=nil) + @root = F.expand_path(root) + @app = app || Rack::File.new(@root) + end + + def call(env) + dup._call(env) + end + + F = ::File + + def _call(env) + @env = env + @script_name = env['SCRIPT_NAME'] + @path_info = Utils.unescape(env['PATH_INFO']) + + if forbidden = check_forbidden + forbidden + else + @path = F.join(@root, @path_info) + list_path + end + end + + def check_forbidden + return unless @path_info.include? ".." + + body = "Forbidden\n" + size = Rack::Utils.bytesize(body) + return [403, {"Content-Type" => "text/plain","Content-Length" => size.to_s}, [body]] + end + + def list_directory + @files = [['../','Parent Directory','','','']] + glob = F.join(@path, '*') + + Dir[glob].sort.each do |node| + stat = stat(node) + next unless stat + basename = F.basename(node) + ext = F.extname(node) + + url = F.join(@script_name, @path_info, basename) + size = stat.size + type = stat.directory? ? 'directory' : Mime.mime_type(ext) + size = stat.directory? ? '-' : filesize_format(size) + mtime = stat.mtime.httpdate + url << '/' if stat.directory? + basename << '/' if stat.directory? + + @files << [ url, basename, size, type, mtime ] + end + + return [ 200, {'Content-Type'=>'text/html; charset=utf-8'}, self ] + end + + def stat(node, max = 10) + F.stat(node) + rescue Errno::ENOENT, Errno::ELOOP + return nil + end + + # TODO: add correct response if not readable, not sure if 404 is the best + # option + def list_path + @stat = F.stat(@path) + + if @stat.readable? + return @app.call(@env) if @stat.file? + return list_directory if @stat.directory? + else + raise Errno::ENOENT, 'No such file or directory' + end + + rescue Errno::ENOENT, Errno::ELOOP + return entity_not_found + end + + def entity_not_found + body = "Entity not found: #{@path_info}\n" + size = Rack::Utils.bytesize(body) + return [404, {"Content-Type" => "text/plain", "Content-Length" => size.to_s}, [body]] + end + + def each + show_path = @path.sub(/^#{@root}/,'') + files = @files.map{|f| DIR_FILE % f }*"\n" + page = DIR_PAGE % [ show_path, show_path , files ] + page.each_line{|l| yield l } + end + + # Stolen from Ramaze + + FILESIZE_FORMAT = [ + ['%.1fT', 1 << 40], + ['%.1fG', 1 << 30], + ['%.1fM', 1 << 20], + ['%.1fK', 1 << 10], + ] + + def filesize_format(int) + FILESIZE_FORMAT.each do |format, size| + return format % (int.to_f / size) if int >= size + end + + int.to_s + 'B' + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/file.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/file.rb new file mode 100644 index 0000000000..fe62bd6b86 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/file.rb @@ -0,0 +1,88 @@ +require 'time' +require 'rack/utils' +require 'rack/mime' + +module Rack + # Rack::File serves files below the +root+ given, according to the + # path info of the Rack request. + # + # Handlers can detect if bodies are a Rack::File, and use mechanisms + # like sendfile on the +path+. + + class File + attr_accessor :root + attr_accessor :path + + alias :to_path :path + + def initialize(root) + @root = root + end + + def call(env) + dup._call(env) + end + + F = ::File + + def _call(env) + @path_info = Utils.unescape(env["PATH_INFO"]) + return forbidden if @path_info.include? ".." + + @path = F.join(@root, @path_info) + + begin + if F.file?(@path) && F.readable?(@path) + serving + else + raise Errno::EPERM + end + rescue SystemCallError + not_found + end + end + + def forbidden + body = "Forbidden\n" + [403, {"Content-Type" => "text/plain", + "Content-Length" => body.size.to_s}, + [body]] + end + + # NOTE: + # We check via File::size? whether this file provides size info + # via stat (e.g. /proc files often don't), otherwise we have to + # figure it out by reading the whole file into memory. And while + # we're at it we also use this as body then. + + def serving + if size = F.size?(@path) + body = self + else + body = [F.read(@path)] + size = Utils.bytesize(body.first) + end + + [200, { + "Last-Modified" => F.mtime(@path).httpdate, + "Content-Type" => Mime.mime_type(F.extname(@path), 'text/plain'), + "Content-Length" => size.to_s + }, body] + end + + def not_found + body = "File not found: #{@path_info}\n" + [404, {"Content-Type" => "text/plain", + "Content-Length" => body.size.to_s}, + [body]] + end + + def each + F.open(@path, "rb") { |file| + while part = file.read(8192) + yield part + end + } + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler.rb new file mode 100644 index 0000000000..1018af64c7 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler.rb @@ -0,0 +1,48 @@ +module Rack + # *Handlers* connect web servers with Rack. + # + # Rack includes Handlers for Mongrel, WEBrick, FastCGI, CGI, SCGI + # and LiteSpeed. + # + # Handlers usually are activated by calling <tt>MyHandler.run(myapp)</tt>. + # A second optional hash can be passed to include server-specific + # configuration. + module Handler + def self.get(server) + return unless server + + if klass = @handlers[server] + obj = Object + klass.split("::").each { |x| obj = obj.const_get(x) } + obj + else + Rack::Handler.const_get(server.capitalize) + end + end + + def self.register(server, klass) + @handlers ||= {} + @handlers[server] = klass + end + + autoload :CGI, "rack/handler/cgi" + autoload :FastCGI, "rack/handler/fastcgi" + autoload :Mongrel, "rack/handler/mongrel" + autoload :EventedMongrel, "rack/handler/evented_mongrel" + autoload :SwiftipliedMongrel, "rack/handler/swiftiplied_mongrel" + autoload :WEBrick, "rack/handler/webrick" + autoload :LSWS, "rack/handler/lsws" + autoload :SCGI, "rack/handler/scgi" + autoload :Thin, "rack/handler/thin" + + register 'cgi', 'Rack::Handler::CGI' + register 'fastcgi', 'Rack::Handler::FastCGI' + register 'mongrel', 'Rack::Handler::Mongrel' + register 'emongrel', 'Rack::Handler::EventedMongrel' + register 'smongrel', 'Rack::Handler::SwiftipliedMongrel' + register 'webrick', 'Rack::Handler::WEBrick' + register 'lsws', 'Rack::Handler::LSWS' + register 'scgi', 'Rack::Handler::SCGI' + register 'thin', 'Rack::Handler::Thin' + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/cgi.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/cgi.rb new file mode 100644 index 0000000000..e38156c7f0 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/cgi.rb @@ -0,0 +1,61 @@ +require 'rack/content_length' + +module Rack + module Handler + class CGI + def self.run(app, options=nil) + serve app + end + + def self.serve(app) + app = ContentLength.new(app) + + env = ENV.to_hash + env.delete "HTTP_CONTENT_LENGTH" + + env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" + + env.update({"rack.version" => [0,1], + "rack.input" => $stdin, + "rack.errors" => $stderr, + + "rack.multithread" => false, + "rack.multiprocess" => true, + "rack.run_once" => true, + + "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http" + }) + + env["QUERY_STRING"] ||= "" + env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] + env["REQUEST_PATH"] ||= "/" + + status, headers, body = app.call(env) + begin + send_headers status, headers + send_body body + ensure + body.close if body.respond_to? :close + end + end + + def self.send_headers(status, headers) + STDOUT.print "Status: #{status}\r\n" + headers.each { |k, vs| + vs.split("\n").each { |v| + STDOUT.print "#{k}: #{v}\r\n" + } + } + STDOUT.print "\r\n" + STDOUT.flush + end + + def self.send_body(body) + body.each { |part| + STDOUT.print part + STDOUT.flush + } + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/evented_mongrel.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/evented_mongrel.rb new file mode 100644 index 0000000000..0f5cbf7293 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/evented_mongrel.rb @@ -0,0 +1,8 @@ +require 'swiftcore/evented_mongrel' + +module Rack + module Handler + class EventedMongrel < Handler::Mongrel + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/fastcgi.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/fastcgi.rb new file mode 100644 index 0000000000..6324c7d274 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/fastcgi.rb @@ -0,0 +1,89 @@ +require 'fcgi' +require 'socket' +require 'rack/content_length' + +module Rack + module Handler + class FastCGI + def self.run(app, options={}) + file = options[:File] and STDIN.reopen(UNIXServer.new(file)) + port = options[:Port] and STDIN.reopen(TCPServer.new(port)) + FCGI.each { |request| + serve request, app + } + end + + module ProperStream # :nodoc: + def each # This is missing by default. + while line = gets + yield line + end + end + + def read(*args) + if args.empty? + super || "" # Empty string on EOF. + else + super + end + end + end + + def self.serve(request, app) + app = Rack::ContentLength.new(app) + + env = request.env + env.delete "HTTP_CONTENT_LENGTH" + + request.in.extend ProperStream + + env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" + + env.update({"rack.version" => [0,1], + "rack.input" => request.in, + "rack.errors" => request.err, + + "rack.multithread" => false, + "rack.multiprocess" => true, + "rack.run_once" => false, + + "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http" + }) + + env["QUERY_STRING"] ||= "" + env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] + env["REQUEST_PATH"] ||= "/" + env.delete "PATH_INFO" if env["PATH_INFO"] == "" + env.delete "CONTENT_TYPE" if env["CONTENT_TYPE"] == "" + env.delete "CONTENT_LENGTH" if env["CONTENT_LENGTH"] == "" + + status, headers, body = app.call(env) + begin + send_headers request.out, status, headers + send_body request.out, body + ensure + body.close if body.respond_to? :close + request.finish + end + end + + def self.send_headers(out, status, headers) + out.print "Status: #{status}\r\n" + headers.each { |k, vs| + vs.split("\n").each { |v| + out.print "#{k}: #{v}\r\n" + } + } + out.print "\r\n" + out.flush + end + + def self.send_body(out, body) + body.each { |part| + out.print part + out.flush + } + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/lsws.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/lsws.rb new file mode 100644 index 0000000000..c65ba3ec8e --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/lsws.rb @@ -0,0 +1,55 @@ +require 'lsapi' +require 'rack/content_length' + +module Rack + module Handler + class LSWS + def self.run(app, options=nil) + while LSAPI.accept != nil + serve app + end + end + def self.serve(app) + app = Rack::ContentLength.new(app) + + env = ENV.to_hash + env.delete "HTTP_CONTENT_LENGTH" + env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" + env.update({"rack.version" => [0,1], + "rack.input" => StringIO.new($stdin.read.to_s), + "rack.errors" => $stderr, + "rack.multithread" => false, + "rack.multiprocess" => true, + "rack.run_once" => false, + "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http" + }) + env["QUERY_STRING"] ||= "" + env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] + env["REQUEST_PATH"] ||= "/" + status, headers, body = app.call(env) + begin + send_headers status, headers + send_body body + ensure + body.close if body.respond_to? :close + end + end + def self.send_headers(status, headers) + print "Status: #{status}\r\n" + headers.each { |k, vs| + vs.split("\n").each { |v| + print "#{k}: #{v}\r\n" + } + } + print "\r\n" + STDOUT.flush + end + def self.send_body(body) + body.each { |part| + print part + STDOUT.flush + } + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/mongrel.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/mongrel.rb new file mode 100644 index 0000000000..f0c0d58330 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/mongrel.rb @@ -0,0 +1,84 @@ +require 'mongrel' +require 'stringio' +require 'rack/content_length' +require 'rack/chunked' + +module Rack + module Handler + class Mongrel < ::Mongrel::HttpHandler + def self.run(app, options={}) + server = ::Mongrel::HttpServer.new(options[:Host] || '0.0.0.0', + options[:Port] || 8080) + # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods. + # Use is similar to #run, replacing the app argument with a hash of + # { path=>app, ... } or an instance of Rack::URLMap. + if options[:map] + if app.is_a? Hash + app.each do |path, appl| + path = '/'+path unless path[0] == ?/ + server.register(path, Rack::Handler::Mongrel.new(appl)) + end + elsif app.is_a? URLMap + app.instance_variable_get(:@mapping).each do |(host, path, appl)| + next if !host.nil? && !options[:Host].nil? && options[:Host] != host + path = '/'+path unless path[0] == ?/ + server.register(path, Rack::Handler::Mongrel.new(appl)) + end + else + raise ArgumentError, "first argument should be a Hash or URLMap" + end + else + server.register('/', Rack::Handler::Mongrel.new(app)) + end + yield server if block_given? + server.run.join + end + + def initialize(app) + @app = Rack::Chunked.new(Rack::ContentLength.new(app)) + end + + def process(request, response) + env = {}.replace(request.params) + env.delete "HTTP_CONTENT_TYPE" + env.delete "HTTP_CONTENT_LENGTH" + + env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" + + env.update({"rack.version" => [0,1], + "rack.input" => request.body || StringIO.new(""), + "rack.errors" => $stderr, + + "rack.multithread" => true, + "rack.multiprocess" => false, # ??? + "rack.run_once" => false, + + "rack.url_scheme" => "http", + }) + env["QUERY_STRING"] ||= "" + env.delete "PATH_INFO" if env["PATH_INFO"] == "" + + status, headers, body = @app.call(env) + + begin + response.status = status.to_i + response.send_status(nil) + + headers.each { |k, vs| + vs.split("\n").each { |v| + response.header[k] = v + } + } + response.send_header + + body.each { |part| + response.write part + response.socket.flush + } + ensure + body.close if body.respond_to? :close + end + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/scgi.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/scgi.rb new file mode 100644 index 0000000000..9495c66374 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/scgi.rb @@ -0,0 +1,59 @@ +require 'scgi' +require 'stringio' +require 'rack/content_length' +require 'rack/chunked' + +module Rack + module Handler + class SCGI < ::SCGI::Processor + attr_accessor :app + + def self.run(app, options=nil) + new(options.merge(:app=>app, + :host=>options[:Host], + :port=>options[:Port], + :socket=>options[:Socket])).listen + end + + def initialize(settings = {}) + @app = Rack::Chunked.new(Rack::ContentLength.new(settings[:app])) + @log = Object.new + def @log.info(*args); end + def @log.error(*args); end + super(settings) + end + + def process_request(request, input_body, socket) + env = {}.replace(request) + env.delete "HTTP_CONTENT_TYPE" + env.delete "HTTP_CONTENT_LENGTH" + env["REQUEST_PATH"], env["QUERY_STRING"] = env["REQUEST_URI"].split('?', 2) + env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] + env["PATH_INFO"] = env["REQUEST_PATH"] + env["QUERY_STRING"] ||= "" + env["SCRIPT_NAME"] = "" + env.update({"rack.version" => [0,1], + "rack.input" => StringIO.new(input_body), + "rack.errors" => $stderr, + + "rack.multithread" => true, + "rack.multiprocess" => true, + "rack.run_once" => false, + + "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http" + }) + status, headers, body = app.call(env) + begin + socket.write("Status: #{status}\r\n") + headers.each do |k, vs| + vs.split("\n").each { |v| socket.write("#{k}: #{v}\r\n")} + end + socket.write("\r\n") + body.each {|s| socket.write(s)} + ensure + body.close if body.respond_to? :close + end + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb new file mode 100644 index 0000000000..4bafd0b953 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/swiftiplied_mongrel.rb @@ -0,0 +1,8 @@ +require 'swiftcore/swiftiplied_mongrel' + +module Rack + module Handler + class SwiftipliedMongrel < Handler::Mongrel + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/thin.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/thin.rb new file mode 100644 index 0000000000..3d4fedff75 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/thin.rb @@ -0,0 +1,18 @@ +require "thin" +require "rack/content_length" +require "rack/chunked" + +module Rack + module Handler + class Thin + def self.run(app, options={}) + app = Rack::Chunked.new(Rack::ContentLength.new(app)) + server = ::Thin::Server.new(options[:Host] || '0.0.0.0', + options[:Port] || 8080, + app) + yield server if block_given? + server.start + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/webrick.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/webrick.rb new file mode 100644 index 0000000000..829e7d6bf8 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/handler/webrick.rb @@ -0,0 +1,67 @@ +require 'webrick' +require 'stringio' +require 'rack/content_length' + +module Rack + module Handler + class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet + def self.run(app, options={}) + server = ::WEBrick::HTTPServer.new(options) + server.mount "/", Rack::Handler::WEBrick, app + trap(:INT) { server.shutdown } + yield server if block_given? + server.start + end + + def initialize(server, app) + super server + @app = Rack::ContentLength.new(app) + end + + def service(req, res) + env = req.meta_vars + env.delete_if { |k, v| v.nil? } + + env.update({"rack.version" => [0,1], + "rack.input" => StringIO.new(req.body.to_s), + "rack.errors" => $stderr, + + "rack.multithread" => true, + "rack.multiprocess" => false, + "rack.run_once" => false, + + "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http" + }) + + env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] + env["QUERY_STRING"] ||= "" + env["REQUEST_PATH"] ||= "/" + if env["PATH_INFO"] == "" + env.delete "PATH_INFO" + else + path, n = req.request_uri.path, env["SCRIPT_NAME"].length + env["PATH_INFO"] = path[n, path.length-n] + end + + status, headers, body = @app.call(env) + begin + res.status = status.to_i + headers.each { |k, vs| + if k.downcase == "set-cookie" + res.cookies.concat vs.split("\n") + else + vs.split("\n").each { |v| + res[k] = v + } + end + } + body.each { |part| + res.body << part + } + ensure + body.close if body.respond_to? :close + end + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/head.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/head.rb new file mode 100644 index 0000000000..deab822a99 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/head.rb @@ -0,0 +1,19 @@ +module Rack + +class Head + def initialize(app) + @app = app + end + + def call(env) + status, headers, body = @app.call(env) + + if env["REQUEST_METHOD"] == "HEAD" + [status, headers, []] + else + [status, headers, body] + end + end +end + +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/lint.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lint.rb new file mode 100644 index 0000000000..44a33ce36e --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lint.rb @@ -0,0 +1,462 @@ +require 'rack/utils' + +module Rack + # Rack::Lint validates your application and the requests and + # responses according to the Rack spec. + + class Lint + def initialize(app) + @app = app + end + + # :stopdoc: + + class LintError < RuntimeError; end + module Assertion + def assert(message, &block) + unless block.call + raise LintError, message + end + end + end + include Assertion + + ## This specification aims to formalize the Rack protocol. You + ## can (and should) use Rack::Lint to enforce it. + ## + ## When you develop middleware, be sure to add a Lint before and + ## after to catch all mistakes. + + ## = Rack applications + + ## A Rack application is an Ruby object (not a class) that + ## responds to +call+. + def call(env=nil) + dup._call(env) + end + + def _call(env) + ## It takes exactly one argument, the *environment* + assert("No env given") { env } + check_env env + + env['rack.input'] = InputWrapper.new(env['rack.input']) + env['rack.errors'] = ErrorWrapper.new(env['rack.errors']) + + ## and returns an Array of exactly three values: + status, headers, @body = @app.call(env) + ## The *status*, + check_status status + ## the *headers*, + check_headers headers + ## and the *body*. + check_content_type status, headers + check_content_length status, headers, env + [status, headers, self] + end + + ## == The Environment + def check_env(env) + ## The environment must be an true instance of Hash (no + ## subclassing allowed) that includes CGI-like headers. + ## The application is free to modify the environment. + assert("env #{env.inspect} is not a Hash, but #{env.class}") { + env.instance_of? Hash + } + + ## + ## The environment is required to include these variables + ## (adopted from PEP333), except when they'd be empty, but see + ## below. + + ## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as + ## "GET" or "POST". This cannot ever + ## be an empty string, and so is + ## always required. + + ## <tt>SCRIPT_NAME</tt>:: The initial portion of the request + ## URL's "path" that corresponds to the + ## application object, so that the + ## application knows its virtual + ## "location". This may be an empty + ## string, if the application corresponds + ## to the "root" of the server. + + ## <tt>PATH_INFO</tt>:: The remainder of the request URL's + ## "path", designating the virtual + ## "location" of the request's target + ## within the application. This may be an + ## empty string, if the request URL targets + ## the application root and does not have a + ## trailing slash. This information should be + ## decoded by the server if it comes from a + ## URL. + + ## <tt>QUERY_STRING</tt>:: The portion of the request URL that + ## follows the <tt>?</tt>, if any. May be + ## empty, but is always required! + + ## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>:: When combined with <tt>SCRIPT_NAME</tt> and <tt>PATH_INFO</tt>, these variables can be used to complete the URL. Note, however, that <tt>HTTP_HOST</tt>, if present, should be used in preference to <tt>SERVER_NAME</tt> for reconstructing the request URL. <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt> can never be empty strings, and so are always required. + + ## <tt>HTTP_</tt> Variables:: Variables corresponding to the + ## client-supplied HTTP request + ## headers (i.e., variables whose + ## names begin with <tt>HTTP_</tt>). The + ## presence or absence of these + ## variables should correspond with + ## the presence or absence of the + ## appropriate HTTP header in the + ## request. + + ## In addition to this, the Rack environment must include these + ## Rack-specific variables: + + ## <tt>rack.version</tt>:: The Array [0,1], representing this version of Rack. + ## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the request URL. + ## <tt>rack.input</tt>:: See below, the input stream. + ## <tt>rack.errors</tt>:: See below, the error stream. + ## <tt>rack.multithread</tt>:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise. + ## <tt>rack.multiprocess</tt>:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise. + ## <tt>rack.run_once</tt>:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar). + + ## The server or the application can store their own data in the + ## environment, too. The keys must contain at least one dot, + ## and should be prefixed uniquely. The prefix <tt>rack.</tt> + ## is reserved for use with the Rack core distribution and must + ## not be used otherwise. + ## + + %w[REQUEST_METHOD SERVER_NAME SERVER_PORT + QUERY_STRING + rack.version rack.input rack.errors + rack.multithread rack.multiprocess rack.run_once].each { |header| + assert("env missing required key #{header}") { env.include? header } + } + + ## The environment must not contain the keys + ## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt> + ## (use the versions without <tt>HTTP_</tt>). + %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header| + assert("env contains #{header}, must use #{header[5,-1]}") { + not env.include? header + } + } + + ## The CGI keys (named without a period) must have String values. + env.each { |key, value| + next if key.include? "." # Skip extensions + assert("env variable #{key} has non-string value #{value.inspect}") { + value.instance_of? String + } + } + + ## + ## There are the following restrictions: + + ## * <tt>rack.version</tt> must be an array of Integers. + assert("rack.version must be an Array, was #{env["rack.version"].class}") { + env["rack.version"].instance_of? Array + } + ## * <tt>rack.url_scheme</tt> must either be +http+ or +https+. + assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") { + %w[http https].include? env["rack.url_scheme"] + } + + ## * There must be a valid input stream in <tt>rack.input</tt>. + check_input env["rack.input"] + ## * There must be a valid error stream in <tt>rack.errors</tt>. + check_error env["rack.errors"] + + ## * The <tt>REQUEST_METHOD</tt> must be a valid token. + assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") { + env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/ + } + + ## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt> + assert("SCRIPT_NAME must start with /") { + !env.include?("SCRIPT_NAME") || + env["SCRIPT_NAME"] == "" || + env["SCRIPT_NAME"] =~ /\A\// + } + ## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt> + assert("PATH_INFO must start with /") { + !env.include?("PATH_INFO") || + env["PATH_INFO"] == "" || + env["PATH_INFO"] =~ /\A\// + } + ## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only. + assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") { + !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/ + } + + ## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be + ## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if + ## <tt>SCRIPT_NAME</tt> is empty. + assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") { + env["SCRIPT_NAME"] || env["PATH_INFO"] + } + ## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty. + assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") { + env["SCRIPT_NAME"] != "/" + } + end + + ## === The Input Stream + def check_input(input) + ## The input stream must respond to +gets+, +each+ and +read+. + [:gets, :each, :read].each { |method| + assert("rack.input #{input} does not respond to ##{method}") { + input.respond_to? method + } + } + end + + class InputWrapper + include Assertion + + def initialize(input) + @input = input + end + + def size + @input.size + end + + def rewind + @input.rewind + end + + ## * +gets+ must be called without arguments and return a string, + ## or +nil+ on EOF. + def gets(*args) + assert("rack.input#gets called with arguments") { args.size == 0 } + v = @input.gets + assert("rack.input#gets didn't return a String") { + v.nil? or v.instance_of? String + } + v + end + + ## * +read+ must be called without or with one integer argument + ## and return a string, or +nil+ on EOF. + def read(*args) + assert("rack.input#read called with too many arguments") { + args.size <= 1 + } + if args.size == 1 + assert("rack.input#read called with non-integer argument") { + args.first.kind_of? Integer + } + end + v = @input.read(*args) + assert("rack.input#read didn't return a String") { + v.nil? or v.instance_of? String + } + v + end + + ## * +each+ must be called without arguments and only yield Strings. + def each(*args) + assert("rack.input#each called with arguments") { args.size == 0 } + @input.each { |line| + assert("rack.input#each didn't yield a String") { + line.instance_of? String + } + yield line + } + end + + ## * +close+ must never be called on the input stream. + def close(*args) + assert("rack.input#close must not be called") { false } + end + end + + ## === The Error Stream + def check_error(error) + ## The error stream must respond to +puts+, +write+ and +flush+. + [:puts, :write, :flush].each { |method| + assert("rack.error #{error} does not respond to ##{method}") { + error.respond_to? method + } + } + end + + class ErrorWrapper + include Assertion + + def initialize(error) + @error = error + end + + ## * +puts+ must be called with a single argument that responds to +to_s+. + def puts(str) + @error.puts str + end + + ## * +write+ must be called with a single argument that is a String. + def write(str) + assert("rack.errors#write not called with a String") { str.instance_of? String } + @error.write str + end + + ## * +flush+ must be called without arguments and must be called + ## in order to make the error appear for sure. + def flush + @error.flush + end + + ## * +close+ must never be called on the error stream. + def close(*args) + assert("rack.errors#close must not be called") { false } + end + end + + ## == The Response + + ## === The Status + def check_status(status) + ## The status, if parsed as integer (+to_i+), must be greater than or equal to 100. + assert("Status must be >=100 seen as integer") { status.to_i >= 100 } + end + + ## === The Headers + def check_headers(header) + ## The header must respond to each, and yield values of key and value. + assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") { + header.respond_to? :each + } + header.each { |key, value| + ## The header keys must be Strings. + assert("header key must be a string, was #{key.class}") { + key.instance_of? String + } + ## The header must not contain a +Status+ key, + assert("header must not contain Status") { key.downcase != "status" } + ## contain keys with <tt>:</tt> or newlines in their name, + assert("header names must not contain : or \\n") { key !~ /[:\n]/ } + ## contain keys names that end in <tt>-</tt> or <tt>_</tt>, + assert("header names must not end in - or _") { key !~ /[-_]\z/ } + ## but only contain keys that consist of + ## letters, digits, <tt>_</tt> or <tt>-</tt> and start with a letter. + assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ } + + ## The values of the header must be Strings, + assert("a header value must be a String, but the value of " + + "'#{key}' is a #{value.class}") { value.kind_of? String } + ## consisting of lines (for multiple header values) seperated by "\n". + value.split("\n").each { |item| + ## The lines must not contain characters below 037. + assert("invalid header value #{key}: #{item.inspect}") { + item !~ /[\000-\037]/ + } + } + } + end + + ## === The Content-Type + def check_content_type(status, headers) + headers.each { |key, value| + ## There must be a <tt>Content-Type</tt>, except when the + ## +Status+ is 1xx, 204 or 304, in which case there must be none + ## given. + if key.downcase == "content-type" + assert("Content-Type header found in #{status} response, not allowed") { + not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i + } + return + end + } + assert("No Content-Type header found") { + Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i + } + end + + ## === The Content-Length + def check_content_length(status, headers, env) + headers.each { |key, value| + if key.downcase == 'content-length' + ## There must not be a <tt>Content-Length</tt> header when the + ## +Status+ is 1xx, 204 or 304. + assert("Content-Length header found in #{status} response, not allowed") { + not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i + } + + bytes = 0 + string_body = true + + if @body.respond_to?(:to_ary) + @body.each { |part| + unless part.kind_of?(String) + string_body = false + break + end + + bytes += Rack::Utils.bytesize(part) + } + + if env["REQUEST_METHOD"] == "HEAD" + assert("Response body was given for HEAD request, but should be empty") { + bytes == 0 + } + else + if string_body + assert("Content-Length header was #{value}, but should be #{bytes}") { + value == bytes.to_s + } + end + end + end + + return + end + } + end + + ## === The Body + def each + @closed = false + ## The Body must respond to #each + @body.each { |part| + ## and must only yield String values. + assert("Body yielded non-string value #{part.inspect}") { + part.instance_of? String + } + yield part + } + ## + ## If the Body responds to #close, it will be called after iteration. + # XXX howto: assert("Body has not been closed") { @closed } + + + ## + ## If the Body responds to #to_path, it must return a String + ## identifying the location of a file whose contents are identical + ## to that produced by calling #each. + + if @body.respond_to?(:to_path) + assert("The file identified by body.to_path does not exist") { + ::File.exist? @body.to_path + } + end + + ## + ## The Body commonly is an Array of Strings, the application + ## instance itself, or a File-like object. + end + + def close + @closed = true + @body.close if @body.respond_to?(:close) + end + + # :startdoc: + + end +end + +## == Thanks +## Some parts of this specification are adopted from PEP333: Python +## Web Server Gateway Interface +## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank +## everyone involved in that effort. diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/lobster.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lobster.rb new file mode 100644 index 0000000000..f63f419a49 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lobster.rb @@ -0,0 +1,65 @@ +require 'zlib' + +require 'rack/request' +require 'rack/response' + +module Rack + # Paste has a Pony, Rack has a Lobster! + class Lobster + LobsterString = Zlib::Inflate.inflate("eJx9kEEOwyAMBO99xd7MAcytUhPlJyj2 + P6jy9i4k9EQyGAnBarEXeCBqSkntNXsi/ZCvC48zGQoZKikGrFMZvgS5ZHd+aGWVuWwhVF0 + t1drVmiR42HcWNz5w3QanT+2gIvTVCiE1lm1Y0eU4JGmIIbaKwextKn8rvW+p5PIwFl8ZWJ + I8jyiTlhTcYXkekJAzTyYN6E08A+dk8voBkAVTJQ==".delete("\n ").unpack("m*")[0]) + + LambdaLobster = lambda { |env| + if env["QUERY_STRING"].include?("flip") + lobster = LobsterString.split("\n"). + map { |line| line.ljust(42).reverse }. + join("\n") + href = "?" + else + lobster = LobsterString + href = "?flip" + end + + content = ["<title>Lobstericious!</title>", + "<pre>", lobster, "</pre>", + "<a href='#{href}'>flip!</a>"] + length = content.inject(0) { |a,e| a+e.size }.to_s + [200, {"Content-Type" => "text/html", "Content-Length" => length}, content] + } + + def call(env) + req = Request.new(env) + if req.GET["flip"] == "left" + lobster = LobsterString.split("\n"). + map { |line| line.ljust(42).reverse }. + join("\n") + href = "?flip=right" + elsif req.GET["flip"] == "crash" + raise "Lobster crashed" + else + lobster = LobsterString + href = "?flip=left" + end + + res = Response.new + res.write "<title>Lobstericious!</title>" + res.write "<pre>" + res.write lobster + res.write "</pre>" + res.write "<p><a href='#{href}'>flip!</a></p>" + res.write "<p><a href='?flip=crash'>crash!</a></p>" + res.finish + end + + end +end + +if $0 == __FILE__ + require 'rack' + require 'rack/showexceptions' + Rack::Handler::WEBrick.run \ + Rack::ShowExceptions.new(Rack::Lint.new(Rack::Lobster.new)), + :Port => 9292 +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/lock.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lock.rb new file mode 100644 index 0000000000..93238528c4 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/lock.rb @@ -0,0 +1,16 @@ +module Rack + class Lock + FLAG = 'rack.multithread'.freeze + + def initialize(app, lock = Mutex.new) + @app, @lock = app, lock + end + + def call(env) + old, env[FLAG] = env[FLAG], false + @lock.synchronize { @app.call(env) } + ensure + env[FLAG] = old + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/methodoverride.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/methodoverride.rb new file mode 100644 index 0000000000..0eed29f471 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/methodoverride.rb @@ -0,0 +1,27 @@ +module Rack + class MethodOverride + HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS) + + METHOD_OVERRIDE_PARAM_KEY = "_method".freeze + HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze + + def initialize(app) + @app = app + end + + def call(env) + if env["REQUEST_METHOD"] == "POST" + req = Request.new(env) + method = req.POST[METHOD_OVERRIDE_PARAM_KEY] || + env[HTTP_METHOD_OVERRIDE_HEADER] + method = method.to_s.upcase + if HTTP_METHODS.include?(method) + env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"] + env["REQUEST_METHOD"] = method + end + end + + @app.call(env) + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/mime.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/mime.rb new file mode 100644 index 0000000000..5a6a73a97b --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/mime.rb @@ -0,0 +1,204 @@ +module Rack + module Mime + # Returns String with mime type if found, otherwise use +fallback+. + # +ext+ should be filename extension in the '.ext' format that + # File.extname(file) returns. + # +fallback+ may be any object + # + # Also see the documentation for MIME_TYPES + # + # Usage: + # Rack::Mime.mime_type('.foo') + # + # This is a shortcut for: + # Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream') + + def mime_type(ext, fallback='application/octet-stream') + MIME_TYPES.fetch(ext, fallback) + end + module_function :mime_type + + # List of most common mime-types, selected various sources + # according to their usefulness in a webserving scope for Ruby + # users. + # + # To amend this list with your local mime.types list you can use: + # + # require 'webrick/httputils' + # list = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types') + # Rack::Mime::MIME_TYPES.merge!(list) + # + # To add the list mongrel provides, use: + # + # require 'mongrel/handlers' + # Rack::Mime::MIME_TYPES.merge!(Mongrel::DirHandler::MIME_TYPES) + + MIME_TYPES = { + ".3gp" => "video/3gpp", + ".a" => "application/octet-stream", + ".ai" => "application/postscript", + ".aif" => "audio/x-aiff", + ".aiff" => "audio/x-aiff", + ".asc" => "application/pgp-signature", + ".asf" => "video/x-ms-asf", + ".asm" => "text/x-asm", + ".asx" => "video/x-ms-asf", + ".atom" => "application/atom+xml", + ".au" => "audio/basic", + ".avi" => "video/x-msvideo", + ".bat" => "application/x-msdownload", + ".bin" => "application/octet-stream", + ".bmp" => "image/bmp", + ".bz2" => "application/x-bzip2", + ".c" => "text/x-c", + ".cab" => "application/vnd.ms-cab-compressed", + ".cc" => "text/x-c", + ".chm" => "application/vnd.ms-htmlhelp", + ".class" => "application/octet-stream", + ".com" => "application/x-msdownload", + ".conf" => "text/plain", + ".cpp" => "text/x-c", + ".crt" => "application/x-x509-ca-cert", + ".css" => "text/css", + ".csv" => "text/csv", + ".cxx" => "text/x-c", + ".deb" => "application/x-debian-package", + ".der" => "application/x-x509-ca-cert", + ".diff" => "text/x-diff", + ".djv" => "image/vnd.djvu", + ".djvu" => "image/vnd.djvu", + ".dll" => "application/x-msdownload", + ".dmg" => "application/octet-stream", + ".doc" => "application/msword", + ".dot" => "application/msword", + ".dtd" => "application/xml-dtd", + ".dvi" => "application/x-dvi", + ".ear" => "application/java-archive", + ".eml" => "message/rfc822", + ".eps" => "application/postscript", + ".exe" => "application/x-msdownload", + ".f" => "text/x-fortran", + ".f77" => "text/x-fortran", + ".f90" => "text/x-fortran", + ".flv" => "video/x-flv", + ".for" => "text/x-fortran", + ".gem" => "application/octet-stream", + ".gemspec" => "text/x-script.ruby", + ".gif" => "image/gif", + ".gz" => "application/x-gzip", + ".h" => "text/x-c", + ".hh" => "text/x-c", + ".htm" => "text/html", + ".html" => "text/html", + ".ico" => "image/vnd.microsoft.icon", + ".ics" => "text/calendar", + ".ifb" => "text/calendar", + ".iso" => "application/octet-stream", + ".jar" => "application/java-archive", + ".java" => "text/x-java-source", + ".jnlp" => "application/x-java-jnlp-file", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".js" => "application/javascript", + ".json" => "application/json", + ".log" => "text/plain", + ".m3u" => "audio/x-mpegurl", + ".m4v" => "video/mp4", + ".man" => "text/troff", + ".mathml" => "application/mathml+xml", + ".mbox" => "application/mbox", + ".mdoc" => "text/troff", + ".me" => "text/troff", + ".mid" => "audio/midi", + ".midi" => "audio/midi", + ".mime" => "message/rfc822", + ".mml" => "application/mathml+xml", + ".mng" => "video/x-mng", + ".mov" => "video/quicktime", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mp4v" => "video/mp4", + ".mpeg" => "video/mpeg", + ".mpg" => "video/mpeg", + ".ms" => "text/troff", + ".msi" => "application/x-msdownload", + ".odp" => "application/vnd.oasis.opendocument.presentation", + ".ods" => "application/vnd.oasis.opendocument.spreadsheet", + ".odt" => "application/vnd.oasis.opendocument.text", + ".ogg" => "application/ogg", + ".p" => "text/x-pascal", + ".pas" => "text/x-pascal", + ".pbm" => "image/x-portable-bitmap", + ".pdf" => "application/pdf", + ".pem" => "application/x-x509-ca-cert", + ".pgm" => "image/x-portable-graymap", + ".pgp" => "application/pgp-encrypted", + ".pkg" => "application/octet-stream", + ".pl" => "text/x-script.perl", + ".pm" => "text/x-script.perl-module", + ".png" => "image/png", + ".pnm" => "image/x-portable-anymap", + ".ppm" => "image/x-portable-pixmap", + ".pps" => "application/vnd.ms-powerpoint", + ".ppt" => "application/vnd.ms-powerpoint", + ".ps" => "application/postscript", + ".psd" => "image/vnd.adobe.photoshop", + ".py" => "text/x-script.python", + ".qt" => "video/quicktime", + ".ra" => "audio/x-pn-realaudio", + ".rake" => "text/x-script.ruby", + ".ram" => "audio/x-pn-realaudio", + ".rar" => "application/x-rar-compressed", + ".rb" => "text/x-script.ruby", + ".rdf" => "application/rdf+xml", + ".roff" => "text/troff", + ".rpm" => "application/x-redhat-package-manager", + ".rss" => "application/rss+xml", + ".rtf" => "application/rtf", + ".ru" => "text/x-script.ruby", + ".s" => "text/x-asm", + ".sgm" => "text/sgml", + ".sgml" => "text/sgml", + ".sh" => "application/x-sh", + ".sig" => "application/pgp-signature", + ".snd" => "audio/basic", + ".so" => "application/octet-stream", + ".svg" => "image/svg+xml", + ".svgz" => "image/svg+xml", + ".swf" => "application/x-shockwave-flash", + ".t" => "text/troff", + ".tar" => "application/x-tar", + ".tbz" => "application/x-bzip-compressed-tar", + ".tcl" => "application/x-tcl", + ".tex" => "application/x-tex", + ".texi" => "application/x-texinfo", + ".texinfo" => "application/x-texinfo", + ".text" => "text/plain", + ".tif" => "image/tiff", + ".tiff" => "image/tiff", + ".torrent" => "application/x-bittorrent", + ".tr" => "text/troff", + ".txt" => "text/plain", + ".vcf" => "text/x-vcard", + ".vcs" => "text/x-vcalendar", + ".vrml" => "model/vrml", + ".war" => "application/java-archive", + ".wav" => "audio/x-wav", + ".wma" => "audio/x-ms-wma", + ".wmv" => "video/x-ms-wmv", + ".wmx" => "video/x-ms-wmx", + ".wrl" => "model/vrml", + ".wsdl" => "application/wsdl+xml", + ".xbm" => "image/x-xbitmap", + ".xhtml" => "application/xhtml+xml", + ".xls" => "application/vnd.ms-excel", + ".xml" => "application/xml", + ".xpm" => "image/x-xpixmap", + ".xsl" => "application/xml", + ".xslt" => "application/xslt+xml", + ".yaml" => "text/yaml", + ".yml" => "text/yaml", + ".zip" => "application/zip", + } + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/mock.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/mock.rb new file mode 100644 index 0000000000..70852da3db --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/mock.rb @@ -0,0 +1,160 @@ +require 'uri' +require 'stringio' +require 'rack/lint' +require 'rack/utils' +require 'rack/response' + +module Rack + # Rack::MockRequest helps testing your Rack application without + # actually using HTTP. + # + # After performing a request on a URL with get/post/put/delete, it + # returns a MockResponse with useful helper methods for effective + # testing. + # + # You can pass a hash with additional configuration to the + # get/post/put/delete. + # <tt>:input</tt>:: A String or IO-like to be used as rack.input. + # <tt>:fatal</tt>:: Raise a FatalWarning if the app writes to rack.errors. + # <tt>:lint</tt>:: If true, wrap the application in a Rack::Lint. + + class MockRequest + class FatalWarning < RuntimeError + end + + class FatalWarner + def puts(warning) + raise FatalWarning, warning + end + + def write(warning) + raise FatalWarning, warning + end + + def flush + end + + def string + "" + end + end + + DEFAULT_ENV = { + "rack.version" => [0,1], + "rack.input" => StringIO.new, + "rack.errors" => StringIO.new, + "rack.multithread" => true, + "rack.multiprocess" => true, + "rack.run_once" => false, + } + + def initialize(app) + @app = app + end + + def get(uri, opts={}) request("GET", uri, opts) end + def post(uri, opts={}) request("POST", uri, opts) end + def put(uri, opts={}) request("PUT", uri, opts) end + def delete(uri, opts={}) request("DELETE", uri, opts) end + + def request(method="GET", uri="", opts={}) + env = self.class.env_for(uri, opts.merge(:method => method)) + + if opts[:lint] + app = Rack::Lint.new(@app) + else + app = @app + end + + errors = env["rack.errors"] + MockResponse.new(*(app.call(env) + [errors])) + end + + # Return the Rack environment used for a request to +uri+. + def self.env_for(uri="", opts={}) + uri = URI(uri) + env = DEFAULT_ENV.dup + + env["REQUEST_METHOD"] = opts[:method] || "GET" + env["SERVER_NAME"] = uri.host || "example.org" + env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80" + env["QUERY_STRING"] = uri.query.to_s + env["PATH_INFO"] = (!uri.path || uri.path.empty?) ? "/" : uri.path + env["rack.url_scheme"] = uri.scheme || "http" + + env["SCRIPT_NAME"] = opts[:script_name] || "" + + if opts[:fatal] + env["rack.errors"] = FatalWarner.new + else + env["rack.errors"] = StringIO.new + end + + opts[:input] ||= "" + if String === opts[:input] + env["rack.input"] = StringIO.new(opts[:input]) + else + env["rack.input"] = opts[:input] + end + + env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s + + opts.each { |field, value| + env[field] = value if String === field + } + + env + end + end + + # Rack::MockResponse provides useful helpers for testing your apps. + # Usually, you don't create the MockResponse on your own, but use + # MockRequest. + + class MockResponse + def initialize(status, headers, body, errors=StringIO.new("")) + @status = status.to_i + + @original_headers = headers + @headers = Rack::Utils::HeaderHash.new + headers.each { |field, values| + @headers[field] = values + @headers[field] = "" if values.empty? + } + + @body = "" + body.each { |part| @body << part } + + @errors = errors.string + end + + # Status + attr_reader :status + + # Headers + attr_reader :headers, :original_headers + + def [](field) + headers[field] + end + + + # Body + attr_reader :body + + def =~(other) + @body =~ other + end + + def match(other) + @body.match other + end + + + # Errors + attr_accessor :errors + + + include Response::Helpers + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/recursive.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/recursive.rb new file mode 100644 index 0000000000..bf8b965925 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/recursive.rb @@ -0,0 +1,57 @@ +require 'uri' + +module Rack + # Rack::ForwardRequest gets caught by Rack::Recursive and redirects + # the current request to the app at +url+. + # + # raise ForwardRequest.new("/not-found") + # + + class ForwardRequest < Exception + attr_reader :url, :env + + def initialize(url, env={}) + @url = URI(url) + @env = env + + @env["PATH_INFO"] = @url.path + @env["QUERY_STRING"] = @url.query if @url.query + @env["HTTP_HOST"] = @url.host if @url.host + @env["HTTP_PORT"] = @url.port if @url.port + @env["rack.url_scheme"] = @url.scheme if @url.scheme + + super "forwarding to #{url}" + end + end + + # Rack::Recursive allows applications called down the chain to + # include data from other applications (by using + # <tt>rack['rack.recursive.include'][...]</tt> or raise a + # ForwardRequest to redirect internally. + + class Recursive + def initialize(app) + @app = app + end + + def call(env) + @script_name = env["SCRIPT_NAME"] + @app.call(env.merge('rack.recursive.include' => method(:include))) + rescue ForwardRequest => req + call(env.merge(req.env)) + end + + def include(env, path) + unless path.index(@script_name) == 0 && (path[@script_name.size] == ?/ || + path[@script_name.size].nil?) + raise ArgumentError, "can only include below #{@script_name}, not #{path}" + end + + env = env.merge("PATH_INFO" => path, "SCRIPT_NAME" => @script_name, + "REQUEST_METHOD" => "GET", + "CONTENT_LENGTH" => "0", "CONTENT_TYPE" => "", + "rack.input" => StringIO.new("")) + @app.call(env) + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/reloader.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/reloader.rb new file mode 100644 index 0000000000..b17d8c0926 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/reloader.rb @@ -0,0 +1,64 @@ +require 'thread' + +module Rack + # Rack::Reloader checks on every request, but at most every +secs+ + # seconds, if a file loaded changed, and reloads it, logging to + # rack.errors. + # + # It is recommended you use ShowExceptions to catch SyntaxErrors etc. + + class Reloader + def initialize(app, secs=10) + @app = app + @secs = secs # reload every @secs seconds max + @last = Time.now + end + + def call(env) + if Time.now > @last + @secs + Thread.exclusive { + reload!(env['rack.errors']) + @last = Time.now + } + end + + @app.call(env) + end + + def reload!(stderr=$stderr) + need_reload = $LOADED_FEATURES.find_all { |loaded| + begin + if loaded =~ /\A[.\/]/ # absolute filename or 1.9 + abs = loaded + else + abs = $LOAD_PATH.map { |path| ::File.join(path, loaded) }. + find { |file| ::File.exist? file } + end + + if abs + ::File.mtime(abs) > @last - @secs rescue false + else + false + end + end + } + + need_reload.each { |l| + $LOADED_FEATURES.delete l + } + + need_reload.each { |to_load| + begin + if require to_load + stderr.puts "#{self.class}: reloaded `#{to_load}'" + end + rescue LoadError, SyntaxError => e + raise e # Possibly ShowExceptions + end + } + + stderr.flush + need_reload + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/request.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/request.rb new file mode 100644 index 0000000000..d77fa26575 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/request.rb @@ -0,0 +1,241 @@ +require 'rack/utils' + +module Rack + # Rack::Request provides a convenient interface to a Rack + # environment. It is stateless, the environment +env+ passed to the + # constructor will be directly modified. + # + # req = Rack::Request.new(env) + # req.post? + # req.params["data"] + # + # The environment hash passed will store a reference to the Request object + # instantiated so that it will only instantiate if an instance of the Request + # object doesn't already exist. + + class Request + # The environment of the request. + attr_reader :env + + def self.new(env) + if self == Rack::Request + env["rack.request"] ||= super + else + super + end + end + + def initialize(env) + @env = env + end + + def body; @env["rack.input"] end + def scheme; @env["rack.url_scheme"] end + def script_name; @env["SCRIPT_NAME"].to_s end + def path_info; @env["PATH_INFO"].to_s end + def port; @env["SERVER_PORT"].to_i end + def request_method; @env["REQUEST_METHOD"] end + def query_string; @env["QUERY_STRING"].to_s end + def content_length; @env['CONTENT_LENGTH'] end + def content_type; @env['CONTENT_TYPE'] end + + # The media type (type/subtype) portion of the CONTENT_TYPE header + # without any media type parameters. e.g., when CONTENT_TYPE is + # "text/plain;charset=utf-8", the media-type is "text/plain". + # + # For more information on the use of media types in HTTP, see: + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7 + def media_type + content_type && content_type.split(/\s*[;,]\s*/, 2)[0].downcase + end + + # The media type parameters provided in CONTENT_TYPE as a Hash, or + # an empty Hash if no CONTENT_TYPE or media-type parameters were + # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8", + # this method responds with the following Hash: + # { 'charset' => 'utf-8' } + def media_type_params + return {} if content_type.nil? + content_type.split(/\s*[;,]\s*/)[1..-1]. + collect { |s| s.split('=', 2) }. + inject({}) { |hash,(k,v)| hash[k.downcase] = v ; hash } + end + + # The character set of the request body if a "charset" media type + # parameter was given, or nil if no "charset" was specified. Note + # that, per RFC2616, text/* media types that specify no explicit + # charset are to be considered ISO-8859-1. + def content_charset + media_type_params['charset'] + end + + def host + # Remove port number. + (@env["HTTP_HOST"] || @env["SERVER_NAME"]).gsub(/:\d+\z/, '') + end + + def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end + def path_info=(s); @env["PATH_INFO"] = s.to_s end + + def get?; request_method == "GET" end + def post?; request_method == "POST" end + def put?; request_method == "PUT" end + def delete?; request_method == "DELETE" end + def head?; request_method == "HEAD" end + + # The set of form-data media-types. Requests that do not indicate + # one of the media types presents in this list will not be eligible + # for form-data / param parsing. + FORM_DATA_MEDIA_TYPES = [ + nil, + 'application/x-www-form-urlencoded', + 'multipart/form-data' + ] + + # Determine whether the request body contains form-data by checking + # the request media_type against registered form-data media-types: + # "application/x-www-form-urlencoded" and "multipart/form-data". The + # list of form-data media types can be modified through the + # +FORM_DATA_MEDIA_TYPES+ array. + def form_data? + FORM_DATA_MEDIA_TYPES.include?(media_type) + end + + # Returns the data recieved in the query string. + def GET + if @env["rack.request.query_string"] == query_string + @env["rack.request.query_hash"] + else + @env["rack.request.query_string"] = query_string + @env["rack.request.query_hash"] = + Utils.parse_nested_query(query_string) + end + end + + # Returns the data recieved in the request body. + # + # This method support both application/x-www-form-urlencoded and + # multipart/form-data. + def POST + if @env["rack.request.form_input"].eql? @env["rack.input"] + @env["rack.request.form_hash"] + elsif form_data? + @env["rack.request.form_input"] = @env["rack.input"] + unless @env["rack.request.form_hash"] = + Utils::Multipart.parse_multipart(env) + form_vars = @env["rack.input"].read + + # Fix for Safari Ajax postings that always append \0 + form_vars.sub!(/\0\z/, '') + + @env["rack.request.form_vars"] = form_vars + @env["rack.request.form_hash"] = Utils.parse_nested_query(form_vars) + + begin + @env["rack.input"].rewind if @env["rack.input"].respond_to?(:rewind) + rescue Errno::ESPIPE + # Handles exceptions raised by input streams that cannot be rewound + # such as when using plain CGI under Apache + end + end + @env["rack.request.form_hash"] + else + {} + end + end + + # The union of GET and POST data. + def params + self.put? ? self.GET : self.GET.update(self.POST) + rescue EOFError => e + self.GET + end + + # shortcut for request.params[key] + def [](key) + params[key.to_s] + end + + # shortcut for request.params[key] = value + def []=(key, value) + params[key.to_s] = value + end + + # like Hash#values_at + def values_at(*keys) + keys.map{|key| params[key] } + end + + # the referer of the client or '/' + def referer + @env['HTTP_REFERER'] || '/' + end + alias referrer referer + + + def cookies + return {} unless @env["HTTP_COOKIE"] + + if @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"] + @env["rack.request.cookie_hash"] + else + @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"] + # According to RFC 2109: + # If multiple cookies satisfy the criteria above, they are ordered in + # the Cookie header such that those with more specific Path attributes + # precede those with less specific. Ordering with respect to other + # attributes (e.g., Domain) is unspecified. + @env["rack.request.cookie_hash"] = + Utils.parse_query(@env["rack.request.cookie_string"], ';,').inject({}) {|h,(k,v)| + h[k] = Array === v ? v.first : v + h + } + end + end + + def xhr? + @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" + end + + # Tries to return a remake of the original request URL as a string. + def url + url = scheme + "://" + url << host + + if scheme == "https" && port != 443 || + scheme == "http" && port != 80 + url << ":#{port}" + end + + url << fullpath + + url + end + + def fullpath + path = script_name + path_info + path << "?" << query_string unless query_string.empty? + path + end + + def accept_encoding + @env["HTTP_ACCEPT_ENCODING"].to_s.split(/,\s*/).map do |part| + m = /^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$/.match(part) # From WEBrick + + if m + [m[1], (m[2] || 1.0).to_f] + else + raise "Invalid value for Accept-Encoding: #{part.inspect}" + end + end + end + + def ip + if addr = @env['HTTP_X_FORWARDED_FOR'] + addr.split(',').last.strip + else + @env['REMOTE_ADDR'] + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/response.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/response.rb new file mode 100644 index 0000000000..caf60d5b19 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/response.rb @@ -0,0 +1,179 @@ +require 'rack/request' +require 'rack/utils' + +module Rack + # Rack::Response provides a convenient interface to create a Rack + # response. + # + # It allows setting of headers and cookies, and provides useful + # defaults (a OK response containing HTML). + # + # You can use Response#write to iteratively generate your response, + # but note that this is buffered by Rack::Response until you call + # +finish+. +finish+ however can take a block inside which calls to + # +write+ are syncronous with the Rack response. + # + # Your application's +call+ should end returning Response#finish. + + class Response + attr_accessor :length + + def initialize(body=[], status=200, header={}, &block) + @status = status + @header = Utils::HeaderHash.new({"Content-Type" => "text/html"}. + merge(header)) + + @writer = lambda { |x| @body << x } + @block = nil + @length = 0 + + @body = [] + + if body.respond_to? :to_str + write body.to_str + elsif body.respond_to?(:each) + body.each { |part| + write part.to_s + } + else + raise TypeError, "stringable or iterable required" + end + + yield self if block_given? + end + + attr_reader :header + attr_accessor :status, :body + + def [](key) + header[key] + end + + def []=(key, value) + header[key] = value + end + + def set_cookie(key, value) + case value + when Hash + domain = "; domain=" + value[:domain] if value[:domain] + path = "; path=" + value[:path] if value[:path] + # According to RFC 2109, we need dashes here. + # N.B.: cgi.rb uses spaces... + expires = "; expires=" + value[:expires].clone.gmtime. + strftime("%a, %d-%b-%Y %H:%M:%S GMT") if value[:expires] + secure = "; secure" if value[:secure] + httponly = "; HttpOnly" if value[:httponly] + value = value[:value] + end + value = [value] unless Array === value + cookie = Utils.escape(key) + "=" + + value.map { |v| Utils.escape v }.join("&") + + "#{domain}#{path}#{expires}#{secure}#{httponly}" + + case self["Set-Cookie"] + when Array + self["Set-Cookie"] << cookie + when String + self["Set-Cookie"] = [self["Set-Cookie"], cookie] + when nil + self["Set-Cookie"] = cookie + end + end + + def delete_cookie(key, value={}) + unless Array === self["Set-Cookie"] + self["Set-Cookie"] = [self["Set-Cookie"]].compact + end + + self["Set-Cookie"].reject! { |cookie| + cookie =~ /\A#{Utils.escape(key)}=/ + } + + set_cookie(key, + {:value => '', :path => nil, :domain => nil, + :expires => Time.at(0) }.merge(value)) + end + + + def finish(&block) + @block = block + + if [204, 304].include?(status.to_i) + header.delete "Content-Type" + [status.to_i, header.to_hash, []] + else + [status.to_i, header.to_hash, self] + end + end + alias to_a finish # For *response + + def each(&callback) + @body.each(&callback) + @writer = callback + @block.call(self) if @block + end + + # Append to body and update Content-Length. + # + # NOTE: Do not mix #write and direct #body access! + # + def write(str) + s = str.to_s + @length += s.size + @writer.call s + + header["Content-Length"] = @length.to_s + str + end + + def close + body.close if body.respond_to?(:close) + end + + def empty? + @block == nil && @body.empty? + end + + alias headers header + + module Helpers + def invalid?; @status < 100 || @status >= 600; end + + def informational?; @status >= 100 && @status < 200; end + def successful?; @status >= 200 && @status < 300; end + def redirection?; @status >= 300 && @status < 400; end + def client_error?; @status >= 400 && @status < 500; end + def server_error?; @status >= 500 && @status < 600; end + + def ok?; @status == 200; end + def forbidden?; @status == 403; end + def not_found?; @status == 404; end + + def redirect?; [301, 302, 303, 307].include? @status; end + def empty?; [201, 204, 304].include? @status; end + + # Headers + attr_reader :headers, :original_headers + + def include?(header) + !!headers[header] + end + + def content_type + headers["Content-Type"] + end + + def content_length + cl = headers["Content-Length"] + cl ? cl.to_i : cl + end + + def location + headers["Location"] + end + end + + include Helpers + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/abstract/id.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/abstract/id.rb new file mode 100644 index 0000000000..218144c17f --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/abstract/id.rb @@ -0,0 +1,142 @@ +# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net +# bugrep: Andreas Zehnder + +require 'time' +require 'rack/request' +require 'rack/response' + +module Rack + + module Session + + module Abstract + + # ID sets up a basic framework for implementing an id based sessioning + # service. Cookies sent to the client for maintaining sessions will only + # contain an id reference. Only #get_session and #set_session are + # required to be overwritten. + # + # All parameters are optional. + # * :key determines the name of the cookie, by default it is + # 'rack.session' + # * :path, :domain, :expire_after, :secure, and :httponly set the related + # cookie options as by Rack::Response#add_cookie + # * :defer will not set a cookie in the response. + # * :renew (implementation dependent) will prompt the generation of a new + # session id, and migration of data to be referenced at the new id. If + # :defer is set, it will be overridden and the cookie will be set. + # * :sidbits sets the number of bits in length that a generated session + # id will be. + # + # These options can be set on a per request basis, at the location of + # env['rack.session.options']. Additionally the id of the session can be + # found within the options hash at the key :id. It is highly not + # recommended to change its value. + # + # Is Rack::Utils::Context compatible. + + class ID + DEFAULT_OPTIONS = { + :path => '/', + :domain => nil, + :expire_after => nil, + :secure => false, + :httponly => true, + :defer => false, + :renew => false, + :sidbits => 128 + } + + attr_reader :key, :default_options + def initialize(app, options={}) + @app = app + @key = options[:key] || "rack.session" + @default_options = self.class::DEFAULT_OPTIONS.merge(options) + end + + def call(env) + context(env) + end + + def context(env, app=@app) + load_session(env) + status, headers, body = app.call(env) + commit_session(env, status, headers, body) + end + + private + + # Generate a new session id using Ruby #rand. The size of the + # session id is controlled by the :sidbits option. + # Monkey patch this to use custom methods for session id generation. + + def generate_sid + "%0#{@default_options[:sidbits] / 4}x" % + rand(2**@default_options[:sidbits] - 1) + end + + # Extracts the session id from provided cookies and passes it and the + # environment to #get_session. It then sets the resulting session into + # 'rack.session', and places options and session metadata into + # 'rack.session.options'. + + def load_session(env) + request = Rack::Request.new(env) + session_id = request.cookies[@key] + + begin + session_id, session = get_session(env, session_id) + env['rack.session'] = session + rescue + env['rack.session'] = Hash.new + end + + env['rack.session.options'] = @default_options. + merge(:id => session_id) + end + + # Acquires the session from the environment and the session id from + # the session options and passes them to #set_session. If successful + # and the :defer option is not true, a cookie will be added to the + # response with the session's id. + + def commit_session(env, status, headers, body) + session = env['rack.session'] + options = env['rack.session.options'] + session_id = options[:id] + + if not session_id = set_session(env, session_id, session, options) + env["rack.errors"].puts("Warning! #{self.class.name} failed to save session. Content dropped.") + [status, headers, body] + elsif options[:defer] and not options[:renew] + env["rack.errors"].puts("Defering cookie for #{session_id}") if $VERBOSE + [status, headers, body] + else + cookie = Hash.new + cookie[:value] = session_id + cookie[:expires] = Time.now + options[:expire_after] unless options[:expire_after].nil? + response = Rack::Response.new(body, status, headers) + response.set_cookie(@key, cookie.merge(options)) + response.to_a + end + end + + # All thread safety and session retrival proceedures should occur here. + # Should return [session_id, session]. + # If nil is provided as the session id, generation of a new valid id + # should occur within. + + def get_session(env, sid) + raise '#get_session not implemented.' + end + + # All thread safety and session storage proceedures should occur here. + # Should return true or false dependant on whether or not the session + # was saved or not. + def set_session(env, sid, session, options) + raise '#set_session not implemented.' + end + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/cookie.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/cookie.rb new file mode 100644 index 0000000000..eace9bd0c6 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/cookie.rb @@ -0,0 +1,91 @@ +require 'openssl' +require 'rack/request' +require 'rack/response' + +module Rack + + module Session + + # Rack::Session::Cookie provides simple cookie based session management. + # The session is a Ruby Hash stored as base64 encoded marshalled data + # set to :key (default: rack.session). + # When the secret key is set, cookie data is checked for data integrity. + # + # Example: + # + # use Rack::Session::Cookie, :key => 'rack.session', + # :domain => 'foo.com', + # :path => '/', + # :expire_after => 2592000, + # :secret => 'change_me' + # + # All parameters are optional. + + class Cookie + + def initialize(app, options={}) + @app = app + @key = options[:key] || "rack.session" + @secret = options[:secret] + @default_options = {:domain => nil, + :path => "/", + :expire_after => nil}.merge(options) + end + + def call(env) + load_session(env) + status, headers, body = @app.call(env) + commit_session(env, status, headers, body) + end + + private + + def load_session(env) + request = Rack::Request.new(env) + session_data = request.cookies[@key] + + if @secret && session_data + session_data, digest = session_data.split("--") + session_data = nil unless digest == generate_hmac(session_data) + end + + begin + session_data = session_data.unpack("m*").first + session_data = Marshal.load(session_data) + env["rack.session"] = session_data + rescue + env["rack.session"] = Hash.new + end + + env["rack.session.options"] = @default_options.dup + end + + def commit_session(env, status, headers, body) + session_data = Marshal.dump(env["rack.session"]) + session_data = [session_data].pack("m*") + + if @secret + session_data = "#{session_data}--#{generate_hmac(session_data)}" + end + + if session_data.size > (4096 - @key.size) + env["rack.errors"].puts("Warning! Rack::Session::Cookie data size exceeds 4K. Content dropped.") + [status, headers, body] + else + options = env["rack.session.options"] + cookie = Hash.new + cookie[:value] = session_data + cookie[:expires] = Time.now + options[:expire_after] unless options[:expire_after].nil? + response = Rack::Response.new(body, status, headers) + response.set_cookie(@key, cookie.merge(options)) + response.to_a + end + end + + def generate_hmac(data) + OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, @secret, data) + end + + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/memcache.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/memcache.rb new file mode 100644 index 0000000000..4a65cbf35d --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/memcache.rb @@ -0,0 +1,109 @@ +# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net + +require 'rack/session/abstract/id' +require 'memcache' + +module Rack + module Session + # Rack::Session::Memcache provides simple cookie based session management. + # Session data is stored in memcached. The corresponding session key is + # maintained in the cookie. + # You may treat Session::Memcache as you would Session::Pool with the + # following caveats. + # + # * Setting :expire_after to 0 would note to the Memcache server to hang + # onto the session data until it would drop it according to it's own + # specifications. However, the cookie sent to the client would expire + # immediately. + # + # Note that memcache does drop data before it may be listed to expire. For + # a full description of behaviour, please see memcache's documentation. + + class Memcache < Abstract::ID + attr_reader :mutex, :pool + DEFAULT_OPTIONS = Abstract::ID::DEFAULT_OPTIONS.merge \ + :namespace => 'rack:session', + :memcache_server => 'localhost:11211' + + def initialize(app, options={}) + super + + @mutex = Mutex.new + @pool = MemCache. + new @default_options[:memcache_server], @default_options + raise 'No memcache servers' unless @pool.servers.any?{|s|s.alive?} + end + + def generate_sid + loop do + sid = super + break sid unless @pool.get(sid, true) + end + end + + def get_session(env, sid) + session = @pool.get(sid) if sid + @mutex.lock if env['rack.multithread'] + unless sid and session + env['rack.errors'].puts("Session '#{sid.inspect}' not found, initializing...") if $VERBOSE and not sid.nil? + session = {} + sid = generate_sid + ret = @pool.add sid, session + raise "Session collision on '#{sid.inspect}'" unless /^STORED/ =~ ret + end + session.instance_variable_set('@old', {}.merge(session)) + return [sid, session] + rescue MemCache::MemCacheError, Errno::ECONNREFUSED # MemCache server cannot be contacted + warn "#{self} is unable to find server." + warn $!.inspect + return [ nil, {} ] + ensure + @mutex.unlock if env['rack.multithread'] + end + + def set_session(env, session_id, new_session, options) + expiry = options[:expire_after] + expiry = expiry.nil? ? 0 : expiry + 1 + + @mutex.lock if env['rack.multithread'] + session = @pool.get(session_id) || {} + if options[:renew] or options[:drop] + @pool.delete session_id + return false if options[:drop] + session_id = generate_sid + @pool.add session_id, 0 # so we don't worry about cache miss on #set + end + old_session = new_session.instance_variable_get('@old') || {} + session = merge_sessions session_id, old_session, new_session, session + @pool.set session_id, session, expiry + return session_id + rescue MemCache::MemCacheError, Errno::ECONNREFUSED # MemCache server cannot be contacted + warn "#{self} is unable to find server." + warn $!.inspect + return false + ensure + @mutex.unlock if env['rack.multithread'] + end + + private + + def merge_sessions sid, old, new, cur=nil + cur ||= {} + unless Hash === old and Hash === new + warn 'Bad old or new sessions provided.' + return cur + end + + delete = old.keys - new.keys + warn "//@#{sid}: delete #{delete*','}" if $VERBOSE and not delete.empty? + delete.each{|k| cur.delete k } + + update = new.keys.select{|k| new[k] != old[k] } + warn "//@#{sid}: update #{update*','}" if $VERBOSE and not update.empty? + update.each{|k| cur[k] = new[k] } + + cur + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/pool.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/pool.rb new file mode 100644 index 0000000000..f6f87408bb --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/session/pool.rb @@ -0,0 +1,100 @@ +# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net +# THANKS: +# apeiros, for session id generation, expiry setup, and threadiness +# sergio, threadiness and bugreps + +require 'rack/session/abstract/id' +require 'thread' + +module Rack + module Session + # Rack::Session::Pool provides simple cookie based session management. + # Session data is stored in a hash held by @pool. + # In the context of a multithreaded environment, sessions being + # committed to the pool is done in a merging manner. + # + # The :drop option is available in rack.session.options if you with to + # explicitly remove the session from the session cache. + # + # Example: + # myapp = MyRackApp.new + # sessioned = Rack::Session::Pool.new(myapp, + # :domain => 'foo.com', + # :expire_after => 2592000 + # ) + # Rack::Handler::WEBrick.run sessioned + + class Pool < Abstract::ID + attr_reader :mutex, :pool + DEFAULT_OPTIONS = Abstract::ID::DEFAULT_OPTIONS.merge :drop => false + + def initialize(app, options={}) + super + @pool = Hash.new + @mutex = Mutex.new + end + + def generate_sid + loop do + sid = super + break sid unless @pool.key? sid + end + end + + def get_session(env, sid) + session = @pool[sid] if sid + @mutex.lock if env['rack.multithread'] + unless sid and session + env['rack.errors'].puts("Session '#{sid.inspect}' not found, initializing...") if $VERBOSE and not sid.nil? + session = {} + sid = generate_sid + @pool.store sid, session + end + session.instance_variable_set('@old', {}.merge(session)) + return [sid, session] + ensure + @mutex.unlock if env['rack.multithread'] + end + + def set_session(env, session_id, new_session, options) + @mutex.lock if env['rack.multithread'] + session = @pool[session_id] + if options[:renew] or options[:drop] + @pool.delete session_id + return false if options[:drop] + session_id = generate_sid + @pool.store session_id, 0 + end + old_session = new_session.instance_variable_get('@old') || {} + session = merge_sessions session_id, old_session, new_session, session + @pool.store session_id, session + return session_id + rescue + warn "#{new_session.inspect} has been lost." + warn $!.inspect + ensure + @mutex.unlock if env['rack.multithread'] + end + + private + + def merge_sessions sid, old, new, cur=nil + cur ||= {} + unless Hash === old and Hash === new + warn 'Bad old or new sessions provided.' + return cur + end + + delete = old.keys - new.keys + warn "//@#{sid}: dropping #{delete*','}" if $DEBUG and not delete.empty? + delete.each{|k| cur.delete k } + + update = new.keys.select{|k| new[k] != old[k] } + warn "//@#{sid}: updating #{update*','}" if $DEBUG and not update.empty? + update.each{|k| cur[k] = new[k] } + + cur + end + end + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/showexceptions.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/showexceptions.rb new file mode 100644 index 0000000000..697bc41fdb --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/showexceptions.rb @@ -0,0 +1,349 @@ +require 'ostruct' +require 'erb' +require 'rack/request' +require 'rack/utils' + +module Rack + # Rack::ShowExceptions catches all exceptions raised from the app it + # wraps. It shows a useful backtrace with the sourcefile and + # clickable context, the whole Rack environment and the request + # data. + # + # Be careful when you use this on public-facing sites as it could + # reveal information helpful to attackers. + + class ShowExceptions + CONTEXT = 7 + + def initialize(app) + @app = app + @template = ERB.new(TEMPLATE) + end + + def call(env) + @app.call(env) + rescue StandardError, LoadError, SyntaxError => e + backtrace = pretty(env, e) + [500, + {"Content-Type" => "text/html", + "Content-Length" => backtrace.join.size.to_s}, + backtrace] + end + + def pretty(env, exception) + req = Rack::Request.new(env) + path = (req.script_name + req.path_info).squeeze("/") + + frames = exception.backtrace.map { |line| + frame = OpenStruct.new + if line =~ /(.*?):(\d+)(:in `(.*)')?/ + frame.filename = $1 + frame.lineno = $2.to_i + frame.function = $4 + + begin + lineno = frame.lineno-1 + lines = ::File.readlines(frame.filename) + frame.pre_context_lineno = [lineno-CONTEXT, 0].max + frame.pre_context = lines[frame.pre_context_lineno...lineno] + frame.context_line = lines[lineno].chomp + frame.post_context_lineno = [lineno+CONTEXT, lines.size].min + frame.post_context = lines[lineno+1..frame.post_context_lineno] + rescue + end + + frame + else + nil + end + }.compact + + env["rack.errors"].puts "#{exception.class}: #{exception.message}" + env["rack.errors"].puts exception.backtrace.map { |l| "\t" + l } + env["rack.errors"].flush + + [@template.result(binding)] + end + + def h(obj) # :nodoc: + case obj + when String + Utils.escape_html(obj) + else + Utils.escape_html(obj.inspect) + end + end + + # :stopdoc: + +# adapted from Django <djangoproject.com> +# Copyright (c) 2005, the Lawrence Journal-World +# Used under the modified BSD license: +# http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5 +TEMPLATE = <<'HTML' +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> +<html lang="en"> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <meta name="robots" content="NONE,NOARCHIVE" /> + <title><%=h exception.class %> at <%=h path %></title> + <style type="text/css"> + html * { padding:0; margin:0; } + body * { padding:10px 20px; } + body * * { padding:0; } + body { font:small sans-serif; } + body>div { border-bottom:1px solid #ddd; } + h1 { font-weight:normal; } + h2 { margin-bottom:.8em; } + h2 span { font-size:80%; color:#666; font-weight:normal; } + h3 { margin:1em 0 .5em 0; } + h4 { margin:0 0 .5em 0; font-weight: normal; } + table { + border:1px solid #ccc; border-collapse: collapse; background:white; } + tbody td, tbody th { vertical-align:top; padding:2px 3px; } + thead th { + padding:1px 6px 1px 3px; background:#fefefe; text-align:left; + font-weight:normal; font-size:11px; border:1px solid #ddd; } + tbody th { text-align:right; color:#666; padding-right:.5em; } + table.vars { margin:5px 0 2px 40px; } + table.vars td, table.req td { font-family:monospace; } + table td.code { width:100%;} + table td.code div { overflow:hidden; } + table.source th { color:#666; } + table.source td { + font-family:monospace; white-space:pre; border-bottom:1px solid #eee; } + ul.traceback { list-style-type:none; } + ul.traceback li.frame { margin-bottom:1em; } + div.context { margin: 10px 0; } + div.context ol { + padding-left:30px; margin:0 10px; list-style-position: inside; } + div.context ol li { + font-family:monospace; white-space:pre; color:#666; cursor:pointer; } + div.context ol.context-line li { color:black; background-color:#ccc; } + div.context ol.context-line li span { float: right; } + div.commands { margin-left: 40px; } + div.commands a { color:black; text-decoration:none; } + #summary { background: #ffc; } + #summary h2 { font-weight: normal; color: #666; } + #summary ul#quicklinks { list-style-type: none; margin-bottom: 2em; } + #summary ul#quicklinks li { float: left; padding: 0 1em; } + #summary ul#quicklinks>li+li { border-left: 1px #666 solid; } + #explanation { background:#eee; } + #template, #template-not-exist { background:#f6f6f6; } + #template-not-exist ul { margin: 0 0 0 20px; } + #traceback { background:#eee; } + #requestinfo { background:#f6f6f6; padding-left:120px; } + #summary table { border:none; background:transparent; } + #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; } + #requestinfo h3 { margin-bottom:-1em; } + .error { background: #ffc; } + .specific { color:#cc3300; font-weight:bold; } + </style> + <script type="text/javascript"> + //<!-- + function getElementsByClassName(oElm, strTagName, strClassName){ + // Written by Jonathan Snook, http://www.snook.ca/jon; + // Add-ons by Robert Nyman, http://www.robertnyman.com + var arrElements = (strTagName == "*" && document.all)? document.all : + oElm.getElementsByTagName(strTagName); + var arrReturnElements = new Array(); + strClassName = strClassName.replace(/\-/g, "\\-"); + var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$$)"); + var oElement; + for(var i=0; i<arrElements.length; i++){ + oElement = arrElements[i]; + if(oRegExp.test(oElement.className)){ + arrReturnElements.push(oElement); + } + } + return (arrReturnElements) + } + function hideAll(elems) { + for (var e = 0; e < elems.length; e++) { + elems[e].style.display = 'none'; + } + } + window.onload = function() { + hideAll(getElementsByClassName(document, 'table', 'vars')); + hideAll(getElementsByClassName(document, 'ol', 'pre-context')); + hideAll(getElementsByClassName(document, 'ol', 'post-context')); + } + function toggle() { + for (var i = 0; i < arguments.length; i++) { + var e = document.getElementById(arguments[i]); + if (e) { + e.style.display = e.style.display == 'none' ? 'block' : 'none'; + } + } + return false; + } + function varToggle(link, id) { + toggle('v' + id); + var s = link.getElementsByTagName('span')[0]; + var uarr = String.fromCharCode(0x25b6); + var darr = String.fromCharCode(0x25bc); + s.innerHTML = s.innerHTML == uarr ? darr : uarr; + return false; + } + //--> + </script> +</head> +<body> + +<div id="summary"> + <h1><%=h exception.class %> at <%=h path %></h1> + <h2><%=h exception.message %></h2> + <table><tr> + <th>Ruby</th> + <td><code><%=h frames.first.filename %></code>: in <code><%=h frames.first.function %></code>, line <%=h frames.first.lineno %></td> + </tr><tr> + <th>Web</th> + <td><code><%=h req.request_method %> <%=h(req.host + path)%></code></td> + </tr></table> + + <h3>Jump to:</h3> + <ul id="quicklinks"> + <li><a href="#get-info">GET</a></li> + <li><a href="#post-info">POST</a></li> + <li><a href="#cookie-info">Cookies</a></li> + <li><a href="#env-info">ENV</a></li> + </ul> +</div> + +<div id="traceback"> + <h2>Traceback <span>(innermost first)</span></h2> + <ul class="traceback"> +<% frames.each { |frame| %> + <li class="frame"> + <code><%=h frame.filename %></code>: in <code><%=h frame.function %></code> + + <% if frame.context_line %> + <div class="context" id="c<%=h frame.object_id %>"> + <% if frame.pre_context %> + <ol start="<%=h frame.pre_context_lineno+1 %>" class="pre-context" id="pre<%=h frame.object_id %>"> + <% frame.pre_context.each { |line| %> + <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h line %></li> + <% } %> + </ol> + <% end %> + + <ol start="<%=h frame.lineno %>" class="context-line"> + <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h frame.context_line %><span>...</span></li></ol> + + <% if frame.post_context %> + <ol start='<%=h frame.lineno+1 %>' class="post-context" id="post<%=h frame.object_id %>"> + <% frame.post_context.each { |line| %> + <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h line %></li> + <% } %> + </ol> + <% end %> + </div> + <% end %> + </li> +<% } %> + </ul> +</div> + +<div id="requestinfo"> + <h2>Request information</h2> + + <h3 id="get-info">GET</h3> + <% unless req.GET.empty? %> + <table class="req"> + <thead> + <tr> + <th>Variable</th> + <th>Value</th> + </tr> + </thead> + <tbody> + <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %> + <tr> + <td><%=h key %></td> + <td class="code"><div><%=h val.inspect %></div></td> + </tr> + <% } %> + </tbody> + </table> + <% else %> + <p>No GET data.</p> + <% end %> + + <h3 id="post-info">POST</h3> + <% unless req.POST.empty? %> + <table class="req"> + <thead> + <tr> + <th>Variable</th> + <th>Value</th> + </tr> + </thead> + <tbody> + <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %> + <tr> + <td><%=h key %></td> + <td class="code"><div><%=h val.inspect %></div></td> + </tr> + <% } %> + </tbody> + </table> + <% else %> + <p>No POST data.</p> + <% end %> + + + <h3 id="cookie-info">COOKIES</h3> + <% unless req.cookies.empty? %> + <table class="req"> + <thead> + <tr> + <th>Variable</th> + <th>Value</th> + </tr> + </thead> + <tbody> + <% req.cookies.each { |key, val| %> + <tr> + <td><%=h key %></td> + <td class="code"><div><%=h val.inspect %></div></td> + </tr> + <% } %> + </tbody> + </table> + <% else %> + <p>No cookie data.</p> + <% end %> + + <h3 id="env-info">Rack ENV</h3> + <table class="req"> + <thead> + <tr> + <th>Variable</th> + <th>Value</th> + </tr> + </thead> + <tbody> + <% env.sort_by { |k, v| k.to_s }.each { |key, val| %> + <tr> + <td><%=h key %></td> + <td class="code"><div><%=h val %></div></td> + </tr> + <% } %> + </tbody> + </table> + +</div> + +<div id="explanation"> + <p> + You're seeing this error because you use <code>Rack::ShowExceptions</code>. + </p> +</div> + +</body> +</html> +HTML + + # :startdoc: + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/showstatus.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/showstatus.rb new file mode 100644 index 0000000000..28258c7c89 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/showstatus.rb @@ -0,0 +1,106 @@ +require 'erb' +require 'rack/request' +require 'rack/utils' + +module Rack + # Rack::ShowStatus catches all empty responses the app it wraps and + # replaces them with a site explaining the error. + # + # Additional details can be put into <tt>rack.showstatus.detail</tt> + # and will be shown as HTML. If such details exist, the error page + # is always rendered, even if the reply was not empty. + + class ShowStatus + def initialize(app) + @app = app + @template = ERB.new(TEMPLATE) + end + + def call(env) + status, headers, body = @app.call(env) + headers = Utils::HeaderHash.new(headers) + empty = headers['Content-Length'].to_i <= 0 + + # client or server error, or explicit message + if (status.to_i >= 400 && empty) || env["rack.showstatus.detail"] + req = Rack::Request.new(env) + message = Rack::Utils::HTTP_STATUS_CODES[status.to_i] || status.to_s + detail = env["rack.showstatus.detail"] || message + body = @template.result(binding) + size = Rack::Utils.bytesize(body) + [status, headers.merge("Content-Type" => "text/html", "Content-Length" => size.to_s), [body]] + else + [status, headers, body] + end + end + + def h(obj) # :nodoc: + case obj + when String + Utils.escape_html(obj) + else + Utils.escape_html(obj.inspect) + end + end + + # :stopdoc: + +# adapted from Django <djangoproject.com> +# Copyright (c) 2005, the Lawrence Journal-World +# Used under the modified BSD license: +# http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5 +TEMPLATE = <<'HTML' +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> +<html lang="en"> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <title><%=h message %> at <%=h req.script_name + req.path_info %></title> + <meta name="robots" content="NONE,NOARCHIVE" /> + <style type="text/css"> + html * { padding:0; margin:0; } + body * { padding:10px 20px; } + body * * { padding:0; } + body { font:small sans-serif; background:#eee; } + body>div { border-bottom:1px solid #ddd; } + h1 { font-weight:normal; margin-bottom:.4em; } + h1 span { font-size:60%; color:#666; font-weight:normal; } + table { border:none; border-collapse: collapse; width:100%; } + td, th { vertical-align:top; padding:2px 3px; } + th { width:12em; text-align:right; color:#666; padding-right:.5em; } + #info { background:#f6f6f6; } + #info ol { margin: 0.5em 4em; } + #info ol li { font-family: monospace; } + #summary { background: #ffc; } + #explanation { background:#eee; border-bottom: 0px none; } + </style> +</head> +<body> + <div id="summary"> + <h1><%=h message %> <span>(<%= status.to_i %>)</span></h1> + <table class="meta"> + <tr> + <th>Request Method:</th> + <td><%=h req.request_method %></td> + </tr> + <tr> + <th>Request URL:</th> + <td><%=h req.url %></td> + </tr> + </table> + </div> + <div id="info"> + <p><%= detail %></p> + </div> + + <div id="explanation"> + <p> + You're seeing this error because you use <code>Rack::ShowStatus</code>. + </p> + </div> +</body> +</html> +HTML + + # :startdoc: + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/static.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/static.rb new file mode 100644 index 0000000000..168e8f83b2 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/static.rb @@ -0,0 +1,38 @@ +module Rack + + # The Rack::Static middleware intercepts requests for static files + # (javascript files, images, stylesheets, etc) based on the url prefixes + # passed in the options, and serves them using a Rack::File object. This + # allows a Rack stack to serve both static and dynamic content. + # + # Examples: + # use Rack::Static, :urls => ["/media"] + # will serve all requests beginning with /media from the "media" folder + # located in the current directory (ie media/*). + # + # use Rack::Static, :urls => ["/css", "/images"], :root => "public" + # will serve all requests beginning with /css or /images from the folder + # "public" in the current directory (ie public/css/* and public/images/*) + + class Static + + def initialize(app, options={}) + @app = app + @urls = options[:urls] || ["/favicon.ico"] + root = options[:root] || Dir.pwd + @file_server = Rack::File.new(root) + end + + def call(env) + path = env["PATH_INFO"] + can_serve = @urls.any? { |url| path.index(url) == 0 } + + if can_serve + @file_server.call(env) + else + @app.call(env) + end + end + + end +end diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/urlmap.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/urlmap.rb new file mode 100644 index 0000000000..0ff32df181 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/urlmap.rb @@ -0,0 +1,55 @@ +module Rack + # Rack::URLMap takes a hash mapping urls or paths to apps, and + # dispatches accordingly. Support for HTTP/1.1 host names exists if + # the URLs start with <tt>http://</tt> or <tt>https://</tt>. + # + # URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part + # relevant for dispatch is in the SCRIPT_NAME, and the rest in the + # PATH_INFO. This should be taken care of when you need to + # reconstruct the URL in order to create links. + # + # URLMap dispatches in such a way that the longest paths are tried + # first, since they are most specific. + + class URLMap + def initialize(map = {}) + remap(map) + end + + def remap(map) + @mapping = map.map { |location, app| + if location =~ %r{\Ahttps?://(.*?)(/.*)} + host, location = $1, $2 + else + host = nil + end + + unless location[0] == ?/ + raise ArgumentError, "paths need to start with /" + end + location = location.chomp('/') + + [host, location, app] + }.sort_by { |(h, l, a)| [-l.size, h.to_s.size] } # Longest path first + end + + def call(env) + path = env["PATH_INFO"].to_s.squeeze("/") + script_name = env['SCRIPT_NAME'] + hHost, sName, sPort = env.values_at('HTTP_HOST','SERVER_NAME','SERVER_PORT') + @mapping.each { |host, location, app| + next unless (hHost == host || sName == host \ + || (host.nil? && (hHost == sName || hHost == sName+':'+sPort))) + next unless location == path[0, location.size] + next unless path[location.size] == nil || path[location.size] == ?/ + + return app.call( + env.merge( + 'SCRIPT_NAME' => (script_name + location), + 'PATH_INFO' => path[location.size..-1])) + } + [404, {"Content-Type" => "text/plain"}, ["Not Found: #{path}"]] + end + end +end + diff --git a/actionpack/lib/action_controller/vendor/rack-1.0/rack/utils.rb b/actionpack/lib/action_controller/vendor/rack-1.0/rack/utils.rb new file mode 100644 index 0000000000..0a61bce707 --- /dev/null +++ b/actionpack/lib/action_controller/vendor/rack-1.0/rack/utils.rb @@ -0,0 +1,392 @@ +require 'set' +require 'tempfile' + +module Rack + # Rack::Utils contains a grab-bag of useful methods for writing web + # applications adopted from all kinds of Ruby libraries. + + module Utils + # Performs URI escaping so that you can construct proper + # query strings faster. Use this rather than the cgi.rb + # version since it's faster. (Stolen from Camping). + def escape(s) + s.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/n) { + '%'+$1.unpack('H2'*$1.size).join('%').upcase + }.tr(' ', '+') + end + module_function :escape + + # Unescapes a URI escaped string. (Stolen from Camping). + def unescape(s) + s.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){ + [$1.delete('%')].pack('H*') + } + end + module_function :unescape + + # Stolen from Mongrel, with some small modifications: + # Parses a query string by breaking it up at the '&' + # and ';' characters. You can also use this to parse + # cookies by changing the characters used in the second + # parameter (which defaults to '&;'). + def parse_query(qs, d = '&;') + params = {} + + (qs || '').split(/[#{d}] */n).each do |p| + k, v = unescape(p).split('=', 2) + + if cur = params[k] + if cur.class == Array + params[k] << v + else + params[k] = [cur, v] + end + else + params[k] = v + end + end + + return params + end + module_function :parse_query + + def parse_nested_query(qs, d = '&;') + params = {} + + (qs || '').split(/[#{d}] */n).each do |p| + k, v = unescape(p).split('=', 2) + normalize_params(params, k, v) + end + + return params + end + module_function :parse_nested_query + + def normalize_params(params, name, v = nil) + name =~ %r([\[\]]*([^\[\]]+)\]*) + k = $1 || '' + after = $' || '' + + return if k.empty? + + if after == "" + params[k] = v + elsif after == "[]" + params[k] ||= [] + raise TypeError unless params[k].is_a?(Array) + params[k] << v + elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$) + child_key = $1 + params[k] ||= [] + raise TypeError unless params[k].is_a?(Array) + if params[k].last.is_a?(Hash) && !params[k].last.key?(child_key) + normalize_params(params[k].last, child_key, v) + else + params[k] << normalize_params({}, child_key, v) + end + else + params[k] ||= {} + params[k] = normalize_params(params[k], after, v) + end + + return params + end + module_function :normalize_params + + def build_query(params) + params.map { |k, v| + if v.class == Array + build_query(v.map { |x| [k, x] }) + else + escape(k) + "=" + escape(v) + end + }.join("&") + end + module_function :build_query + + # Escape ampersands, brackets and quotes to their HTML/XML entities. + def escape_html(string) + string.to_s.gsub("&", "&"). + gsub("<", "<"). + gsub(">", ">"). + gsub("'", "'"). + gsub('"', """) + end + module_function :escape_html + + def select_best_encoding(available_encodings, accept_encoding) + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html + + expanded_accept_encoding = + accept_encoding.map { |m, q| + if m == "*" + (available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] } + else + [[m, q]] + end + }.inject([]) { |mem, list| + mem + list + } + + encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m } + + unless encoding_candidates.include?("identity") + encoding_candidates.push("identity") + end + + expanded_accept_encoding.find_all { |m, q| + q == 0.0 + }.each { |m, _| + encoding_candidates.delete(m) + } + + return (encoding_candidates & available_encodings)[0] + end + module_function :select_best_encoding + + # Return the bytesize of String; uses String#length under Ruby 1.8 and + # String#bytesize under 1.9. + if ''.respond_to?(:bytesize) + def bytesize(string) + string.bytesize + end + else + def bytesize(string) + string.size + end + end + module_function :bytesize + + # Context allows the use of a compatible middleware at different points + # in a request handling stack. A compatible middleware must define + # #context which should take the arguments env and app. The first of which + # would be the request environment. The second of which would be the rack + # application that the request would be forwarded to. + class Context + attr_reader :for, :app + + def initialize(app_f, app_r) + raise 'running context does not respond to #context' unless app_f.respond_to? :context + @for, @app = app_f, app_r + end + + def call(env) + @for.context(env, @app) + end + + def recontext(app) + self.class.new(@for, app) + end + + def context(env, app=@app) + recontext(app).call(env) + end + end + + # A case-insensitive Hash that preserves the original case of a + # header when set. + class HeaderHash < Hash + def initialize(hash={}) + @names = {} + hash.each { |k, v| self[k] = v } + end + + def to_hash + inject({}) do |hash, (k,v)| + if v.respond_to? :to_ary + hash[k] = v.to_ary.join("\n") + else + hash[k] = v + end + hash + end + end + + def [](k) + super @names[k.downcase] + end + + def []=(k, v) + delete k + @names[k.downcase] = k + super k, v + end + + def delete(k) + super @names.delete(k.downcase) + end + + def include?(k) + @names.has_key? k.downcase + end + + alias_method :has_key?, :include? + alias_method :member?, :include? + alias_method :key?, :include? + + def merge!(other) + other.each { |k, v| self[k] = v } + self + end + + def merge(other) + hash = dup + hash.merge! other + end + end + + # Every standard HTTP code mapped to the appropriate message. + # Stolen from Mongrel. + HTTP_STATUS_CODES = { + 100 => 'Continue', + 101 => 'Switching Protocols', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 307 => 'Temporary Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported' + } + + # Responses with HTTP status codes that should not have an entity body + STATUS_WITH_NO_ENTITY_BODY = Set.new((100..199).to_a << 204 << 304) + + # A multipart form data parser, adapted from IOWA. + # + # Usually, Rack::Request#POST takes care of calling this. + + module Multipart + EOL = "\r\n" + + def self.parse_multipart(env) + unless env['CONTENT_TYPE'] =~ + %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n + nil + else + boundary = "--#{$1}" + + params = {} + buf = "" + content_length = env['CONTENT_LENGTH'].to_i + input = env['rack.input'] + + boundary_size = boundary.size + EOL.size + bufsize = 16384 + + content_length -= boundary_size + + status = input.read(boundary_size) + raise EOFError, "bad content body" unless status == boundary + EOL + + rx = /(?:#{EOL})?#{Regexp.quote boundary}(#{EOL}|--)/n + + loop { + head = nil + body = '' + filename = content_type = name = nil + + until head && buf =~ rx + if !head && i = buf.index("\r\n\r\n") + head = buf.slice!(0, i+2) # First \r\n + buf.slice!(0, 2) # Second \r\n + + filename = head[/Content-Disposition:.* filename="?([^\";]*)"?/ni, 1] + content_type = head[/Content-Type: (.*)\r\n/ni, 1] + name = head[/Content-Disposition:.* name="?([^\";]*)"?/ni, 1] + + if filename + body = Tempfile.new("RackMultipart") + body.binmode if body.respond_to?(:binmode) + end + + next + end + + # Save the read body part. + if head && (boundary_size+4 < buf.size) + body << buf.slice!(0, buf.size - (boundary_size+4)) + end + + c = input.read(bufsize < content_length ? bufsize : content_length) + raise EOFError, "bad content body" if c.nil? || c.empty? + buf << c + content_length -= c.size + end + + # Save the rest. + if i = buf.index(rx) + body << buf.slice!(0, i) + buf.slice!(0, boundary_size+2) + + content_length = -1 if $1 == "--" + end + + if filename == "" + # filename is blank which means no file has been selected + data = nil + elsif filename + body.rewind + + # Take the basename of the upload's original filename. + # This handles the full Windows paths given by Internet Explorer + # (and perhaps other broken user agents) without affecting + # those which give the lone filename. + filename =~ /^(?:.*[:\\\/])?(.*)/m + filename = $1 + + data = {:filename => filename, :type => content_type, + :name => name, :tempfile => body, :head => head} + else + data = body + end + + Utils.normalize_params(params, name, data) unless data.nil? + + break if buf.empty? || content_length == -1 + } + + begin + input.rewind if input.respond_to?(:rewind) + rescue Errno::ESPIPE + # Handles exceptions raised by input streams that cannot be rewound + # such as when using plain CGI under Apache + end + + params + end + end + end + end +end diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index a2c14f7ea2..7d47a1566e 100755 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -31,7 +31,7 @@ module ActionDispatch # <tt>:get</tt>. If the request \method is not listed in the HTTP_METHODS # constant above, an UnknownHttpMethod exception is raised. def request_method - HTTP_METHOD_LOOKUP[super] || raise(ActionController::UnknownHttpMethod, "#{super}, accepted HTTP methods are #{HTTP_METHODS.to_sentence}") + @request_method ||= HTTP_METHOD_LOOKUP[super] || raise(ActionController::UnknownHttpMethod, "#{super}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") end # Returns the HTTP request \method used for action processing as a @@ -431,15 +431,15 @@ EOM FORM_DATA_MEDIA_TYPES.include?(content_type.to_s) end - # Override Rack's GET method to support nested query strings + # Override Rack's GET method to support indifferent access def GET - @env["action_controller.request.query_parameters"] ||= UrlEncodedPairParser.parse_query_parameters(query_string) + @env["action_controller.request.query_parameters"] ||= normalize_parameters(super) end alias_method :query_parameters, :GET - # Override Rack's POST method to support nested query strings + # Override Rack's POST method to support indifferent access def POST - @env["action_controller.request.request_parameters"] ||= UrlEncodedPairParser.parse_hash_parameters(super) + @env["action_controller.request.request_parameters"] ||= normalize_parameters(super) end alias_method :request_parameters, :POST @@ -456,6 +456,7 @@ EOM end def reset_session + @env['rack.session.options'].delete(:id) @env['rack.session'] = {} end @@ -475,5 +476,28 @@ EOM def named_host?(host) !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host)) end + + # Convert nested Hashs to HashWithIndifferentAccess and replace + # file upload hashs with UploadedFile objects + def normalize_parameters(value) + case value + when Hash + if value.has_key?(:tempfile) + upload = value[:tempfile] + upload.extend(UploadedFile) + upload.original_path = value[:filename] + upload.content_type = value[:type] + upload + else + h = {} + value.each { |k, v| h[k] = normalize_parameters(v) } + h.with_indifferent_access + end + when Array + value.map { |e| normalize_parameters(e) } + else + value + end + end end end diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index e1d8ee3527..ecf40b8103 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -40,14 +40,28 @@ module ActionDispatch # :nodoc: delegate :default_charset, :to => 'ActionController::Base' def initialize - @status = 200 - @header = DEFAULT_HEADERS.dup + super + @header = Rack::Utils::HeaderHash.new(DEFAULT_HEADERS) + @session, @assigns = [], [] + end - @writer = lambda { |x| @body << x } - @block = nil + def body + str = '' + each { |part| str << part.to_s } + str + end - @body = "", - @session, @assigns = [], [] + def body=(body) + @body = + if body.is_a?(String) + [body] + else + body + end + end + + def body_parts + @body end def location; headers['Location'] end @@ -144,7 +158,6 @@ module ActionDispatch # :nodoc: set_content_length! convert_content_type! convert_language! - convert_expires! convert_cookies! end @@ -153,7 +166,7 @@ module ActionDispatch # :nodoc: @writer = lambda { |x| callback.call(x) } @body.call(self, self) elsif @body.is_a?(String) - @body.each_line(&callback) + callback.call(@body) else @body.each(&callback) end @@ -163,37 +176,20 @@ module ActionDispatch # :nodoc: end def write(str) - @writer.call str.to_s + str = str.to_s + @writer.call str str end - # Over Rack::Response#set_cookie to add HttpOnly option def set_cookie(key, value) - case value - when Hash - domain = "; domain=" + value[:domain] if value[:domain] - path = "; path=" + value[:path] if value[:path] - # According to RFC 2109, we need dashes here. - # N.B.: cgi.rb uses spaces... - expires = "; expires=" + value[:expires].clone.gmtime. - strftime("%a, %d-%b-%Y %H:%M:%S GMT") if value[:expires] - secure = "; secure" if value[:secure] - httponly = "; HttpOnly" if value[:http_only] - value = value[:value] - end - value = [value] unless Array === value - cookie = ::Rack::Utils.escape(key) + "=" + - value.map { |v| ::Rack::Utils.escape v }.join("&") + - "#{domain}#{path}#{expires}#{secure}#{httponly}" - - case self["Set-Cookie"] - when Array - self["Set-Cookie"] << cookie - when String - self["Set-Cookie"] = [self["Set-Cookie"], cookie] - when nil - self["Set-Cookie"] = cookie + if value.has_key?(:http_only) + ActiveSupport::Deprecation.warn( + "The :http_only option in ActionController::Response#set_cookie " + + "has been renamed. Please use :httponly instead.", caller) + value[:httponly] ||= value.delete(:http_only) end + + super(key, value) end private @@ -205,7 +201,7 @@ module ActionDispatch # :nodoc: if request && request.etag_matches?(etag) self.status = '304 Not Modified' - self.body = '' + self.body = [] end set_conditional_cache_control! @@ -214,7 +210,11 @@ module ActionDispatch # :nodoc: def nonempty_ok_response? ok = !status || status.to_s[0..2] == '200' - ok && body.is_a?(String) && !body.empty? + ok && string_body? + end + + def string_body? + !body_parts.respond_to?(:call) && body_parts.any? && body_parts.all? { |part| part.is_a?(String) } end def set_conditional_cache_control! @@ -235,8 +235,8 @@ module ActionDispatch # :nodoc: headers.delete('Content-Length') elsif length = headers['Content-Length'] headers['Content-Length'] = length.to_s - elsif !body.respond_to?(:call) && (!status || status.to_s[0..2] != '304') - headers["Content-Length"] = body.size.to_s + elsif string_body? && (!status || status.to_s[0..2] != '304') + headers["Content-Length"] = Rack::Utils.bytesize(body).to_s end end @@ -244,10 +244,6 @@ module ActionDispatch # :nodoc: headers["Content-Language"] = headers.delete("language") if headers["language"] end - def convert_expires! - headers["Expires"] = headers.delete("") if headers["expires"] - end - def convert_cookies! headers['Set-Cookie'] = Array(headers['Set-Cookie']).compact end diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 879d98fbdb..6c039cf62d 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -17,16 +17,11 @@ module ActionDispatch @loaded = false end - def id - load! unless @loaded - @id - end - def session_id ActiveSupport::Deprecation.warn( - "ActionController::Session::AbstractStore::SessionHash#session_id" + - "has been deprecated.Please use #id instead.", caller) - id + "ActionController::Session::AbstractStore::SessionHash#session_id " + + "has been deprecated. Please use request.session_options[:id] instead.", caller) + @env[ENV_SESSION_OPTIONS_KEY][:id] end def [](key) @@ -47,20 +42,45 @@ module ActionDispatch def data ActiveSupport::Deprecation.warn( - "ActionController::Session::AbstractStore::SessionHash#data" + - "has been deprecated.Please use #to_hash instead.", caller) + "ActionController::Session::AbstractStore::SessionHash#data " + + "has been deprecated. Please use #to_hash instead.", caller) to_hash end + def inspect + load! unless @loaded + super + end + private def loaded? @loaded end def load! - @id, session = @by.send(:load_session, @env) - replace(session) - @loaded = true + stale_session_check! do + id, session = @by.send(:load_session, @env) + (@env[ENV_SESSION_OPTIONS_KEY] ||= {})[:id] = id + replace(session) + @loaded = true + end + end + + def stale_session_check! + yield + rescue ArgumentError => argument_error + if argument_error.message =~ %r{undefined class/module ([\w:]*\w)} + begin + # Note that the regexp does not allow $1 to end with a ':' + $1.constantize + rescue LoadError, NameError => const_error + raise ActionController::SessionRestoreError, "Session contains objects whose class definition isn\\'t available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: \#{const_error.message} [\#{const_error.class}])\n" + end + + retry + else + raise + end end end @@ -107,11 +127,7 @@ module ActionDispatch if !session_data.is_a?(AbstractStore::SessionHash) || session_data.send(:loaded?) || options[:expire_after] session_data.send(:load!) if session_data.is_a?(AbstractStore::SessionHash) && !session_data.send(:loaded?) - if session_data.is_a?(AbstractStore::SessionHash) - sid = session_data.id - else - sid = generate_sid - end + sid = options[:id] || generate_sid unless set_session(env, sid, session_data.to_hash) return response @@ -128,12 +144,9 @@ module ActionDispatch cookie << "; HttpOnly" if options[:httponly] headers = response[1] - case a = headers[SET_COOKIE] - when Array - a << cookie - when String - headers[SET_COOKIE] = [a, cookie] - when nil + unless headers[SET_COOKIE].blank? + headers[SET_COOKIE] << "\n#{cookie}" + else headers[SET_COOKIE] = cookie end end diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb index ec93f66a88..433c4cc070 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb @@ -88,7 +88,7 @@ module ActionDispatch def call(env) env[ENV_SESSION_KEY] = AbstractStore::SessionHash.new(self, env) - env[ENV_SESSION_OPTIONS_KEY] = @default_options + env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup status, headers, body = @app.call(env) @@ -108,12 +108,9 @@ module ActionDispatch end cookie = build_cookie(@key, cookie.merge(options)) - case headers[HTTP_SET_COOKIE] - when Array - headers[HTTP_SET_COOKIE] << cookie - when String - headers[HTTP_SET_COOKIE] = [headers[HTTP_SET_COOKIE], cookie] - when nil + unless headers[HTTP_SET_COOKIE].blank? + headers[HTTP_SET_COOKIE] << "\n#{cookie}" + else headers[HTTP_SET_COOKIE] = cookie end end @@ -133,7 +130,7 @@ module ActionDispatch expires = "; expires=" + value[:expires].clone.gmtime. strftime("%a, %d-%b-%Y %H:%M:%S GMT") if value[:expires] secure = "; secure" if value[:secure] - httponly = "; httponly" if value[:httponly] + httponly = "; HttpOnly" if value[:httponly] value = value[:value] end value = [value] unless Array === value diff --git a/actionpack/lib/action_dispatch/rack.rb b/actionpack/lib/action_dispatch/rack.rb index 69df9dac06..89087c124f 100644 --- a/actionpack/lib/action_dispatch/rack.rb +++ b/actionpack/lib/action_dispatch/rack.rb @@ -1,3 +1,3 @@ -require 'action_dispatch/rack/lock' -require 'action_dispatch/rack/multipart' -require 'action_dispatch/rack/parse_query' +# require 'action_dispatch/rack/lock' +# require 'action_dispatch/rack/multipart' +# require 'action_dispatch/rack/parse_query' diff --git a/actionpack/lib/action_dispatch/rack/lock.rb b/actionpack/lib/action_dispatch/rack/lock.rb deleted file mode 100644 index 9bf1889065..0000000000 --- a/actionpack/lib/action_dispatch/rack/lock.rb +++ /dev/null @@ -1,21 +0,0 @@ -module Rack - # Rack::Lock was commited to Rack core - # http://github.com/rack/rack/commit/7409b0c - # Remove this when Rack 1.0 is released - unless defined? Lock - class Lock - FLAG = 'rack.multithread'.freeze - - def initialize(app, lock = Mutex.new) - @app, @lock = app, lock - end - - def call(env) - old, env[FLAG] = env[FLAG], false - @lock.synchronize { @app.call(env) } - ensure - env[FLAG] = old - end - end - end -end diff --git a/actionpack/lib/action_dispatch/rack/multipart.rb b/actionpack/lib/action_dispatch/rack/multipart.rb deleted file mode 100644 index 3b142307e9..0000000000 --- a/actionpack/lib/action_dispatch/rack/multipart.rb +++ /dev/null @@ -1,22 +0,0 @@ -module Rack - module Utils - module Multipart - class << self - def parse_multipart_with_rewind(env) - result = parse_multipart_without_rewind(env) - - begin - env['rack.input'].rewind if env['rack.input'].respond_to?(:rewind) - rescue Errno::ESPIPE - # Handles exceptions raised by input streams that cannot be rewound - # such as when using plain CGI under Apache - end - - result - end - - alias_method_chain :parse_multipart, :rewind - end - end - end -end diff --git a/actionpack/lib/action_dispatch/rack/parse_query.rb b/actionpack/lib/action_dispatch/rack/parse_query.rb deleted file mode 100644 index 15de720f14..0000000000 --- a/actionpack/lib/action_dispatch/rack/parse_query.rb +++ /dev/null @@ -1,18 +0,0 @@ -# Rack does not automatically cleanup Safari 2 AJAX POST body -# This has not yet been commited to Rack, please +1 this ticket: -# http://rack.lighthouseapp.com/projects/22435/tickets/19 - -module Rack - module Utils - alias_method :parse_query_without_ajax_body_cleanup, :parse_query - module_function :parse_query_without_ajax_body_cleanup - - def parse_query(qs, d = '&;') - qs = qs.to_s.dup - qs.chop! if qs[-1] == 0 - qs.gsub!(/&_=$/, '') - parse_query_without_ajax_body_cleanup(qs, d) - end - module_function :parse_query - end -end diff --git a/actionpack/lib/action_dispatch/utils/middleware_stack.rb b/actionpack/lib/action_dispatch/utils/middleware_stack.rb index 924e3dbbc2..ee5f28d5cb 100644 --- a/actionpack/lib/action_dispatch/utils/middleware_stack.rb +++ b/actionpack/lib/action_dispatch/utils/middleware_stack.rb @@ -27,7 +27,9 @@ module ActionDispatch end def klass - if @klass.is_a?(Class) + if @klass.respond_to?(:call) + @klass.call + elsif @klass.is_a?(Class) @klass else @klass.to_s.constantize @@ -37,6 +39,8 @@ module ActionDispatch end def active? + return false unless klass + if @conditional.respond_to?(:call) @conditional.call else @@ -63,11 +67,17 @@ module ActionDispatch def build(app) if block - klass.new(app, *args, &block) + klass.new(app, *build_args, &block) else - klass.new(app, *args) + klass.new(app, *build_args) end end + + private + + def build_args + Array(args).map { |arg| arg.respond_to?(:call) ? arg.call : arg } + end end def initialize(*args, &block) diff --git a/actionpack/lib/action_dispatch/utils/url_encoded_pair_parser.rb b/actionpack/lib/action_dispatch/utils/url_encoded_pair_parser.rb deleted file mode 100644 index f2e832a977..0000000000 --- a/actionpack/lib/action_dispatch/utils/url_encoded_pair_parser.rb +++ /dev/null @@ -1,155 +0,0 @@ -module ActionDispatch - class UrlEncodedPairParser < StringScanner #:nodoc: - class << self - def parse_query_parameters(query_string) - return {} if query_string.blank? - - pairs = query_string.split('&').collect do |chunk| - next if chunk.empty? - key, value = chunk.split('=', 2) - next if key.empty? - value = value.nil? ? nil : CGI.unescape(value) - [ CGI.unescape(key), value ] - end.compact - - new(pairs).result - end - - def parse_hash_parameters(params) - parser = new - - params = params.dup - until params.empty? - for key, value in params - if key.blank? - params.delete(key) - elsif value.is_a?(Array) - parser.parse(key, get_typed_value(value.shift)) - params.delete(key) if value.empty? - else - parser.parse(key, get_typed_value(value)) - params.delete(key) - end - end - end - - parser.result - end - - private - def get_typed_value(value) - case value - when String - value - when NilClass - '' - when Array - value.map { |v| get_typed_value(v) } - when Hash - if value.has_key?(:tempfile) && value[:filename].any? - upload = value[:tempfile] - upload.extend(UploadedFile) - upload.original_path = value[:filename] - upload.content_type = value[:type] - upload - else - nil - end - else - raise "Unknown form value: #{value.inspect}" - end - end - end - - attr_reader :top, :parent, :result - - def initialize(pairs = []) - super('') - @result = {} - pairs.each { |key, value| parse(key, value) } - end - - KEY_REGEXP = %r{([^\[\]=&]+)} - BRACKETED_KEY_REGEXP = %r{\[([^\[\]=&]+)\]} - - # Parse the query string - def parse(key, value) - self.string = key - @top, @parent = result, nil - - # First scan the bare key - key = scan(KEY_REGEXP) or return - key = post_key_check(key) - - # Then scan as many nestings as present - until eos? - r = scan(BRACKETED_KEY_REGEXP) or return - key = self[1] - key = post_key_check(key) - end - - bind(key, value) - end - - private - # After we see a key, we must look ahead to determine our next action. Cases: - # - # [] follows the key. Then the value must be an array. - # = follows the key. (A value comes next) - # & or the end of string follows the key. Then the key is a flag. - # otherwise, a hash follows the key. - def post_key_check(key) - if scan(/\[\]/) # a[b][] indicates that b is an array - container(key, Array) - nil - elsif check(/\[[^\]]/) # a[b] indicates that a is a hash - container(key, Hash) - nil - else # End of key? We do nothing. - key - end - end - - # Add a container to the stack. - def container(key, klass) - type_conflict! klass, top[key] if top.is_a?(Hash) && top.key?(key) && ! top[key].is_a?(klass) - value = bind(key, klass.new) - type_conflict! klass, value unless value.is_a?(klass) - push(value) - end - - # Push a value onto the 'stack', which is actually only the top 2 items. - def push(value) - @parent, @top = @top, value - end - - # Bind a key (which may be nil for items in an array) to the provided value. - def bind(key, value) - if top.is_a? Array - if key - if top[-1].is_a?(Hash) && ! top[-1].key?(key) - top[-1][key] = value - else - top << {key => value}.with_indifferent_access - end - push top.last - return top[key] - else - top << value - return value - end - elsif top.is_a? Hash - key = CGI.unescape(key) - parent << (@top = {}) if top.key?(key) && parent.is_a?(Array) - top[key] ||= value - return top[key] - else - raise ArgumentError, "Don't know what to do: top is #{top.inspect}" - end - end - - def type_conflict!(klass, value) - raise TypeError, "Conflicting types for parameter containers. Expected an instance of #{klass} but found an instance of #{value.class}. This can be caused by colliding Array and Hash parameters like qs[]=value&qs[key]=value. (The parameters received were #{value.inspect}.)" - end - end -end diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb index f20e44a7d5..e0aa2a5f2f 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 = 2 STRING = [MAJOR, MINOR, TINY].join('.') end diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index ada9052073..efed19a21d 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -182,6 +182,15 @@ module ActionView #:nodoc: # that alert()s the caught exception (and then re-raises it). cattr_accessor :debug_rjs + # Specify whether templates should be cached. Otherwise the file we be read everytime it is accessed. + # 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.nil? ? !ActiveSupport::Dependencies.load? : cache_template_loading) + end + attr_internal :request delegate :controller_path, :to => :controller, :allow_nil => true @@ -217,10 +226,12 @@ module ActionView #:nodoc: @formats = formats || [:html] @assigns = assigns_for_first_render @assigns_added = nil - @_render_stack = [] @controller = controller @helpers = ProxyModule.new(self) self.view_paths = view_paths + + @_first_render = nil + @_current_render = nil end attr_reader :view_paths @@ -232,7 +243,25 @@ module ActionView #:nodoc: # Access the current template being rendered. # Returns a ActionView::Template object. def template - @_render_stack.last + @_current_render + end + + def template=(template) #:nodoc: + @_first_render ||= template + @_current_render = template + end + + def with_template(current_template) + last_template, self.template = template, current_template + yield + ensure + self.template = last_template + end + + def punctuate_body!(part) + flush_output_buffer + response.body_parts << part + nil end private diff --git a/actionpack/lib/action_view/helpers/active_record_helper.rb b/actionpack/lib/action_view/helpers/active_record_helper.rb index 8b56d241ae..7c0dfdab10 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 @@ -194,11 +194,11 @@ module ActionView options[:header_message] else object_name = options[:object_name].to_s.gsub('_', ' ') - object_name = I18n.t(object_name, :default => object_name, :scope => [:activerecord, :models], :count => 1) + object_name = I18n.t(options[:object_name].to_s, :default => object_name, :scope => [:activerecord, :models], :count => 1) 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/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb index f6abea38ed..a32beb6100 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb @@ -516,7 +516,8 @@ module ActionView def compute_public_path(source, dir, ext = nil, include_host = true) has_request = @controller.respond_to?(:request) - if ext && (File.extname(source).blank? || File.exist?(File.join(ASSETS_DIR, dir, "#{source}.#{ext}"))) + source_ext = File.extname(source)[1..-1] + if ext && (source_ext.blank? || (ext != source_ext && File.exist?(File.join(ASSETS_DIR, dir, "#{source}.#{ext}")))) source += ".#{ext}" end diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb index cd25684940..dc4497581c 100644 --- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb +++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb @@ -30,7 +30,7 @@ module ActionView # app/views/posts/index.atom.builder: # atom_feed do |feed| # feed.title("My great blog!") - # feed.updated((@posts.first.created_at)) + # feed.updated(@posts.first.created_at) # # for post in @posts # feed.entry(post) do |entry| diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb index e86ca27f31..9e39536653 100644 --- a/actionpack/lib/action_view/helpers/capture_helper.rb +++ b/actionpack/lib/action_view/helpers/capture_helper.rb @@ -131,6 +131,14 @@ module ActionView ensure self.output_buffer = old_buffer end + + # Add the output buffer to the response body and start a new one. + def flush_output_buffer #:nodoc: + if output_buffer && output_buffer != '' + response.body_parts << output_buffer + self.output_buffer = '' + end + end end end end diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index b4c1adbe76..c74909a360 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -876,8 +876,8 @@ module ActionView input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '') end - # Given an ordering of datetime components, create the selection html - # and join them with their appropriate seperators + # Given an ordering of datetime components, create the selection HTML + # and join them with their appropriate separators. def build_selects_from_types(order) select = '' order.reverse.each do |type| @@ -931,7 +931,7 @@ module ActionView end def default_datetime(options) - return if options[:include_blank] + return if options[:include_blank] || options[:prompt] case options[:default] when nil diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index a85751c657..a59829b23f 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? @@ -269,10 +298,12 @@ module ActionView options[:url] ||= polymorphic_path(object_or_array) end - # Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes - # fields_for suitable for specifying additional model objects in the same form: + # Creates a scope around a specific model object like form_for, but + # doesn't create the form tags themselves. This makes fields_for suitable + # for specifying additional model objects in the same form. + # + # === Generic Examples # - # ==== Examples # <% form_for @person, :url => { :action => "update" } do |person_form| %> # First name: <%= person_form.text_field :first_name %> # Last name : <%= person_form.text_field :last_name %> @@ -282,20 +313,166 @@ module ActionView # <% end %> # <% end %> # - # ...or if you have an object that needs to be represented as a different parameter, like a Client that acts as a Person: + # ...or if you have an object that needs to be represented as a different + # parameter, like a Client that acts as a Person: # # <% fields_for :person, @client do |permission_fields| %> # Admin?: <%= permission_fields.check_box :admin %> # <% end %> # - # ...or if you don't have an object, just a name of the parameter + # ...or if you don't have an object, just a name of the parameter: # # <% fields_for :person do |permission_fields| %> # Admin?: <%= permission_fields.check_box :admin %> # <% end %> # - # Note: This also works for the methods in FormOptionHelper and DateHelper that are designed to work with an object as base, - # like FormOptionHelper#collection_select and DateHelper#datetime_select. + # Note: This also works for the methods in FormOptionHelper and + # DateHelper that are designed to work with an object as base, like + # FormOptionHelper#collection_select and DateHelper#datetime_select. + # + # === Nested Attributes Examples + # + # When the object belonging to the current scope has a nested attribute + # writer for a certain attribute, fields_for will yield a new scope + # for that attribute. This allows you to create forms that set or change + # the attributes of a parent object and its associations in one go. + # + # Nested attribute writers are normal setter methods named after an + # association. The most common way of defining these writers is either + # with +accepts_nested_attributes_for+ in a model definition or by + # defining a method with the proper name. For example: the attribute + # writer for the association <tt>:address</tt> is called + # <tt>address_attributes=</tt>. + # + # Whether a one-to-one or one-to-many style form builder will be yielded + # depends on whether the normal reader method returns a _single_ object + # or an _array_ of objects. + # + # ==== One-to-one + # + # Consider a Person class which returns a _single_ Address from the + # <tt>address</tt> reader method and responds to the + # <tt>address_attributes=</tt> writer method: + # + # class Person + # def address + # @address + # end + # + # def address_attributes=(attributes) + # # Process the attributes hash + # end + # end + # + # This model can now be used with a nested fields_for, like so: + # + # <% form_for @person, :url => { :action => "update" } do |person_form| %> + # ... + # <% person_form.fields_for :address do |address_fields| %> + # Street : <%= address_fields.text_field :street %> + # Zip code: <%= address_fields.text_field :zip_code %> + # <% end %> + # <% end %> + # + # When address is already an association on a Person you can use + # +accepts_nested_attributes_for+ to define the writer method for you: + # + # class Person < ActiveRecord::Base + # has_one :address + # accepts_nested_attributes_for :address + # end + # + # If you want to destroy the associated model through the form, you have + # to enable it first using the <tt>:allow_destroy</tt> option for + # +accepts_nested_attributes_for+: + # + # class Person < ActiveRecord::Base + # has_one :address + # accepts_nested_attributes_for :address, :allow_destroy => true + # end + # + # Now, when you use a form element with the <tt>_delete</tt> parameter, + # with a value that evaluates to +true+, you will destroy the associated + # model (eg. 1, '1', true, or 'true'): + # + # <% form_for @person, :url => { :action => "update" } do |person_form| %> + # ... + # <% person_form.fields_for :address do |address_fields| %> + # ... + # Delete: <%= address_fields.check_box :_delete %> + # <% end %> + # <% end %> + # + # ==== One-to-many + # + # Consider a Person class which returns an _array_ of Project instances + # from the <tt>projects</tt> reader method and responds to the + # <tt>projects_attributes=</tt> writer method: + # + # class Person + # def projects + # [@project1, @project2] + # end + # + # def projects_attributes=(attributes) + # # Process the attributes hash + # end + # end + # + # This model can now be used with a nested fields_for. The block given to + # the nested fields_for call will be repeated for each instance in the + # collection: + # + # <% form_for @person, :url => { :action => "update" } do |person_form| %> + # ... + # <% person_form.fields_for :projects do |project_fields| %> + # <% if project_fields.object.active? %> + # Name: <%= project_fields.text_field :name %> + # <% end %> + # <% end %> + # <% end %> + # + # It's also possible to specify the instance to be used: + # + # <% form_for @person, :url => { :action => "update" } do |person_form| %> + # ... + # <% @person.projects.each do |project| %> + # <% if project.active? %> + # <% person_form.fields_for :projects, project do |project_fields| %> + # Name: <%= project_fields.text_field :name %> + # <% end %> + # <% end %> + # <% end %> + # <% end %> + # + # When projects is already an association on Person you can use + # +accepts_nested_attributes_for+ to define the writer method for you: + # + # class Person < ActiveRecord::Base + # has_many :projects + # accepts_nested_attributes_for :projects + # end + # + # If you want to destroy any of the associated models through the + # form, you have to enable it first using the <tt>:allow_destroy</tt> + # option for +accepts_nested_attributes_for+: + # + # class Person < ActiveRecord::Base + # has_many :projects + # accepts_nested_attributes_for :projects, :allow_destroy => true + # end + # + # This will allow you to specify which models to destroy in the + # attributes hash by adding a form element for the <tt>_delete</tt> + # parameter with a value that evaluates to +true+ + # (eg. 1, '1', true, or 'true'): + # + # <% form_for @person, :url => { :action => "update" } do |person_form| %> + # ... + # <% person_form.fields_for :projects do |project_fields| %> + # Delete: <%= project_fields.check_box :_delete %> + # <% end %> + # <% end %> def fields_for(record_or_name_or_array, *args, &block) raise ArgumentError, "Missing block" unless block_given? options = args.extract_options! @@ -451,7 +628,7 @@ module ActionView # # The HTML specification says unchecked check boxes are not successful, and # thus web browsers do not send them. Unfortunately this introduces a gotcha: - # if an Invoice model has a +paid+ flag, and in the form that edits a paid + # if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid # invoice the user unchecks its check box, no +paid+ parameter is sent. So, # any mass-assignment idiom like # @@ -459,12 +636,15 @@ module ActionView # # wouldn't update the flag. # - # To prevent this the helper generates a hidden field with the same name as - # the checkbox after the very check box. So, the client either sends only the - # hidden field (representing the check box is unchecked), or both fields. - # Since the HTML specification says key/value pairs have to be sent in the - # same order they appear in the form and Rails parameters extraction always - # gets the first occurrence of any given key, that works in ordinary forms. + # To prevent this the helper generates an auxiliary hidden field before + # the very check box. The hidden field has the same name and its + # attributes mimick an unchecked check box. + # + # This way, the client either sends only the hidden field (representing + # the check box is unchecked), or both fields. Since the HTML specification + # says key/value pairs have to be sent in the same order they appear in the + # form, and parameters extraction gets the last occurrence of any repeated + # key in the query string, that works for ordinary forms. # # Unfortunately that workaround does not work when the check box goes # within an array-like parameter, as in @@ -475,22 +655,26 @@ module ActionView # <% end %> # # because parameter name repetition is precisely what Rails seeks to distinguish - # the elements of the array. + # the elements of the array. For each item with a checked check box you + # get an extra ghost item with only that attribute, assigned to "0". + # + # In that case it is preferable to either use +check_box_tag+ or to use + # hashes instead of arrays. # # ==== Examples # # Let's say that @post.validated? is 1: # check_box("post", "validated") - # # => <input type="checkbox" id="post_validated" name="post[validated]" value="1" /> - # # <input name="post[validated]" type="hidden" value="0" /> + # # => <input name="post[validated]" type="hidden" value="0" /> + # # <input type="checkbox" id="post_validated" name="post[validated]" value="1" /> # # # Let's say that @puppy.gooddog is "no": # check_box("puppy", "gooddog", {}, "yes", "no") - # # => <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" /> - # # <input name="puppy[gooddog]" type="hidden" value="no" /> + # # => <input name="puppy[gooddog]" type="hidden" value="no" /> + # # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" /> # # check_box("eula", "accepted", { :class => 'eula_check' }, "yes", "no") - # # => <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" /> - # # <input name="eula[accepted]" type="hidden" value="no" /> + # # => <input name="eula[accepted]" type="hidden" value="no" /> + # # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" /> # def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0") InstanceTag.new(object_name, method, self, options.delete(:object)).to_check_box_tag(options, checked_value, unchecked_value) @@ -498,8 +682,10 @@ module ActionView # Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the - # radio button will be checked. Additional options on the input tag can be passed as a - # hash with +options+. + # radio button will be checked. + # + # To force the radio button to be checked pass <tt>:checked => true</tt> in the + # +options+ hash. You may pass HTML options there as well. # # ==== Examples # # Let's say that @post.category returns "rails": @@ -605,7 +791,9 @@ module ActionView end options["checked"] = "checked" if checked add_default_name_and_id(options) - tag("input", options) << tag("input", "name" => options["name"], "type" => "hidden", "value" => options['disabled'] && checked ? checked_value : unchecked_value) + hidden = tag("input", "name" => options["name"], "type" => "hidden", "value" => options['disabled'] && checked ? checked_value : unchecked_value) + checkbox = tag("input", options) + hidden + checkbox end def to_boolean_select_tag(options = {}) @@ -758,9 +946,18 @@ 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 - name = "#{object_name}#{index}[#{record_or_name_or_array}]" + if nested_attributes_association?(record_or_name_or_array) + return fields_for_with_nested_attributes(record_or_name_or_array, args, block) + else + name = "#{object_name}#{index}[#{record_or_name_or_array}]" + end when Array object = record_or_name_or_array.last name = "#{object_name}#{index}[#{ActionController::RecordIdentifier.singular_class_name(object)}]" @@ -802,6 +999,43 @@ module ActionView def objectify_options(options) @default_options.merge(options.merge(:object => @object)) end + + def nested_attributes_association?(association_name) + @object.respond_to?("#{association_name}_attributes=") + end + + def fields_for_with_nested_attributes(association_name, args, block) + name = "#{object_name}[#{association_name}_attributes]" + association = @object.send(association_name) + explicit_object = args.first if args.first.respond_to?(:new_record?) + + if association.is_a?(Array) + children = explicit_object ? [explicit_object] : association + explicit_child_index = args.last[:child_index] if args.last.is_a?(Hash) + + children.map do |child| + fields_for_nested_model("#{name}[#{explicit_child_index || nested_child_index}]", child, args, block) + end.join + else + fields_for_nested_model(name, explicit_object || association, args, block) + end + end + + def fields_for_nested_model(name, object, args, block) + if object.new_record? + @template.fields_for(name, object, *args, &block) + else + @template.fields_for(name, object, *args) do |builder| + @template.concat builder.hidden_field(:id) + block.call(builder) + end + end + end + + def nested_child_index + @nested_child_index ||= -1 + @nested_child_index += 1 + end end end @@ -809,4 +1043,4 @@ module ActionView cattr_accessor :default_form_builder self.default_form_builder = ::ActionView::Helpers::FormBuilder end -end +end
\ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 54c82cbd1d..6b385ef77d 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -6,9 +6,7 @@ module ActionView module Helpers # Provides a number of methods for turning different kinds of containers into a set of option tags. # == Options - # The <tt>collection_select</tt>, <tt>country_select</tt>, <tt>select</tt>, - # and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, - # a hash. + # The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash: # # * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element. # @@ -28,7 +26,7 @@ module ActionView # # Example with @post.person_id => 2: # - # select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, {:include_blank => 'None'}) + # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:include_blank => 'None'}) # # could become: # @@ -43,7 +41,7 @@ module ActionView # # Example: # - # select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'}) + # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'}) # # could become: # @@ -68,6 +66,36 @@ module ActionView # <option value="rock">rock</option> # <option value="country">country</option> # </select> + # + # * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output. + # + # Example: + # + # select("post", "category", Post::CATEGORIES, {:disabled => 'restricted'}) + # + # could become: + # + # <select name="post[category]"> + # <option></option> + # <option>joke</option> + # <option>poem</option> + # <option disabled="disabled">restricted</option> + # </select> + # + # When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled. + # + # Example: + # + # collection_select(:post, :category_id, Category.all, :id, :name, {:disabled => lambda{|category| category.archived? }}) + # + # If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return: + # <select name="post[category_id]"> + # <option value="1" disabled="disabled">2008 stuff</option> + # <option value="2" disabled="disabled">Christmas</option> + # <option value="3">Jokes</option> + # <option value="4">Poems</option> + # </select> + # module FormOptionsHelper include ERB::Util @@ -76,7 +104,7 @@ module ActionView # See options_for_select for the required format of the choices parameter. # # Example with @post.person_id => 1: - # select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true }) + # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true }) # # could become: # @@ -94,7 +122,8 @@ module ActionView # In addition, this allows a single partial to be used to generate form inputs for both edit and create forms. # # By default, <tt>post.person_id</tt> is the selected option. Specify <tt>:selected => value</tt> to use a different selection - # or <tt>:selected => nil</tt> to leave all options unselected. + # or <tt>:selected => nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option + # tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled. def select(object, method, choices, options = {}, html_options = {}) InstanceTag.new(object, method, self, options.delete(:object)).to_select_tag(choices, options, html_options) end @@ -120,7 +149,7 @@ module ActionView # end # # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>): - # collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true}) + # collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true}) # # If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return: # <select name="post[author_id]"> @@ -186,14 +215,29 @@ module ActionView # options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"]) # <option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option> # + # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value + # or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags. + # + # Examples: + # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => "Super Platinum") + # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> + # + # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => ["Advanced", "Super Platinum"]) + # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced" disabled="disabled">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> + # + # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :selected => "Free", :disabled => "Super Platinum") + # <option value="Free" selected="selected">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> + # # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. def options_for_select(container, selected = nil) container = container.to_a if Hash === container + selected, disabled = extract_selected_and_disabled(selected) options_for_select = container.inject([]) do |options, element| text, value = option_text_and_value(element) selected_attribute = ' selected="selected"' if option_value_selected?(value, selected) - options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}>#{html_escape(text.to_s)}</option>) + disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled) + options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}#{disabled_attribute}>#{html_escape(text.to_s)}</option>) end options_for_select.join("\n") @@ -209,8 +253,15 @@ module ActionView # This is more often than not used inside a #select_tag like this example: # select_tag 'person', options_from_collection_for_select(@people, 'id', 'name') # - # If +selected+ is specified, the element returning a match on +value_method+ will get the selected option tag. - # Be sure to specify the same class as the +value_method+ when specifying a selected option. + # If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+ + # will be selected option tag(s). + # + # If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous + # function are the selected values. + # + # +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required. + # + # Be sure to specify the same class as the +value_method+ when specifying selected or disabled options. # Failure to do this will produce undesired results. Example: # options_from_collection_for_select(@people, 'id', 'name', '1') # Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string) @@ -220,7 +271,12 @@ module ActionView options = collection.map do |element| [element.send(text_method), element.send(value_method)] end - options_for_select(options, selected) + selected, disabled = extract_selected_and_disabled(selected) + select_deselect = {} + select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected) + select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled) + + options_for_select(options, select_deselect) end # Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but @@ -238,7 +294,8 @@ module ActionView # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag. # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags, # which will have the +selected+ attribute set. Corresponds to the return value of one of the calls - # to +option_key_method+. If +nil+, no selection is made. + # to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are + # to be specified. # # Example object structure for use with this method: # class Continent < ActiveRecord::Base @@ -388,6 +445,24 @@ module ActionView value == selected end end + + def extract_selected_and_disabled(selected) + if selected.is_a?(Hash) + [selected[:selected], selected[:disabled]] + else + [selected, nil] + end + end + + def extract_values_from_collection(collection, value_method, selected) + if selected.is_a?(Proc) + collection.map do |element| + element.send(value_method) if selected.call(element) + end.compact + else + selected + end + end end class InstanceTag #:nodoc: @@ -398,16 +473,18 @@ module ActionView add_default_name_and_id(html_options) value = value(object) selected_value = options.has_key?(:selected) ? options[:selected] : value - content_tag("select", add_options(options_for_select(choices, selected_value), options, selected_value), html_options) + disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil + content_tag("select", add_options(options_for_select(choices, :selected => selected_value, :disabled => disabled_value), options, selected_value), html_options) end def to_collection_select_tag(collection, value_method, text_method, options, html_options) html_options = html_options.stringify_keys add_default_name_and_id(html_options) value = value(object) + disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil selected_value = options.has_key?(:selected) ? options[:selected] : value content_tag( - "select", add_options(options_from_collection_for_select(collection, value_method, text_method, selected_value), options, value), html_options + "select", add_options(options_from_collection_for_select(collection, value_method, text_method, :selected => selected_value, :disabled => disabled_value), options, value), html_options ) end 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..dea958deaf 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 @@ -138,7 +140,7 @@ module ActionView # number_with_delimiter(12345678) # => 12,345,678 # number_with_delimiter(12345678.05) # => 12,345,678.05 # number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678 - # number_with_delimiter(12345678, :seperator => ",") # => 12,345,678 + # number_with_delimiter(12345678, :separator => ",") # => 12,345,678 # number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",") # # => 98 765 432,98 # diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb index 99676a9c27..6bad11e354 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/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index b1eb6891fa..573b99b96e 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -107,7 +107,7 @@ module ActionView text else match = Array(phrases).map { |p| Regexp.escape(p) }.join('|') - text.gsub(/(#{match})(?!(?:[^<]*?)?(?:["'])[^<>]*>)/i, options[:highlighter]) + text.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter]) end end @@ -324,7 +324,7 @@ module ActionView # Turns all URLs and e-mail addresses into clickable links. The <tt>:link</tt> option # will limit what should be linked. You can add HTML attributes to the links using - # <tt>:href_options</tt>. Possible values for <tt>:link</tt> are <tt>:all</tt> (default), + # <tt>:html</tt>. Possible values for <tt>:link</tt> are <tt>:all</tt> (default), # <tt>:email_addresses</tt>, and <tt>:urls</tt>. If a block is given, each URL and # e-mail address is yielded and the result is used as the link text. # @@ -341,7 +341,7 @@ module ActionView # # => "Visit http://www.loudthinking.com/ or e-mail <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>" # # post_body = "Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com." - # auto_link(post_body, :href_options => { :target => '_blank' }) do |text| + # auto_link(post_body, :html => { :target => '_blank' }) do |text| # truncate(text, 15) # end # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.m...</a>. @@ -359,7 +359,7 @@ module ActionView # auto_link(post_body, :all, :target => "_blank") # => Once upon\na time # # => "Welcome to my new blog at <a href=\"http://www.myblog.com/\" target=\"_blank\">http://www.myblog.com</a>. # Please e-mail me at <a href=\"mailto:me@email.com\">me@email.com</a>." - def auto_link(text, *args, &block)#link = :all, href_options = {}, &block) + def auto_link(text, *args, &block)#link = :all, html = {}, &block) return '' if text.blank? options = args.size == 2 ? {} : args.extract_options! # this is necessary because the old auto_link API has a Hash as its last parameter @@ -536,8 +536,9 @@ module ActionView text.gsub(AUTO_LINK_RE) do href = $& punctuation = '' - # detect already linked URLs - if $` =~ /<a\s[^>]*href="$/ + left, right = $`, $' + # detect already linked URLs and URLs in the middle of a tag + if left =~ /<[^>]+$/ && right =~ /^[^>]*>/ # do not change string; URL is alreay linked href else diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb index dc41ef5305..4aed10f640 100644 --- a/actionpack/lib/action_view/helpers/translation_helper.rb +++ b/actionpack/lib/action_view/helpers/translation_helper.rb @@ -3,19 +3,37 @@ require 'action_view/helpers/tag_helper' module ActionView module Helpers module TranslationHelper + # Delegates to I18n#translate but also performs two additional functions. First, it'll catch MissingTranslationData exceptions + # and turn them into inline spans that contains the missing key, such that you can see in a view what is missing where. + # + # Second, it'll scope the key by the current partial if the key starts with a period. So if you call translate(".foo") from the + # people/index.html.erb template, you'll actually be calling I18n.translate("people.index.foo"). This makes it less repetitive + # to translate many keys within the same partials and gives you a simple framework for scoping them consistently. If you don't + # prepend the key with a period, nothing is converted. def translate(key, options = {}) options[:raise] = true - I18n.translate(key, options) + I18n.translate(scope_key_by_partial(key), options) rescue I18n::MissingTranslationData => e keys = I18n.send(:normalize_translation_keys, e.locale, e.key, e.options[:scope]) content_tag('span', keys.join(', '), :class => 'translation_missing') end alias :t :translate + # Delegates to I18n.localize with no additional functionality. def localize(*args) I18n.localize *args end alias :l :localize + + + private + def scope_key_by_partial(key) + if key.to_s.first == "." + template.path_without_format_and_extension.gsub(%r{/_?}, ".") + key.to_s + else + key + end + end end end end
\ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 2e0eb8766b..36e0a78e93 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -507,7 +507,30 @@ module ActionView # current_page?(:controller => 'shop', :action => 'checkout') # # => true # - # current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc) + # current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc') + # # => false + # + # current_page?(:action => 'checkout') + # # => true + # + # current_page?(:controller => 'library', :action => 'checkout') + # # => false + # + # Let's say we're in the <tt>/shop/checkout?order=desc&page=1</tt> action. + # + # current_page?(:action => 'process') + # # => false + # + # current_page?(:controller => 'shop', :action => 'checkout') + # # => true + # + # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'1') + # # => true + # + # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page=>'2') + # # => false + # + # current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc') # # => false # # current_page?(:action => 'checkout') @@ -516,7 +539,7 @@ module ActionView # current_page?(:controller => 'library', :action => 'checkout') # # => false def current_page?(options) - url_string = CGI.escapeHTML(url_for(options)) + url_string = CGI.unescapeHTML(url_for(options)) request = @controller.request # We ignore any extra parameters in the request_uri if the # submitted url doesn't have any either. This lets the function diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb index 6c6d2ff979..b6bb9942ee 100644 --- a/actionpack/lib/action_view/paths.rb +++ b/actionpack/lib/action_view/paths.rb @@ -2,7 +2,11 @@ module ActionView #:nodoc: class PathSet < Array #:nodoc: def self.type_cast(obj) if obj.is_a?(String) - Template::EagerPath.new(obj) + if !Object.const_defined?(:Rails) || Rails.configuration.cache_classes + Template::EagerPath.new(obj) + else + Template::Path.new(obj) + end else obj end @@ -56,7 +60,7 @@ module ActionView #:nodoc: false 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(/^\//, '') @@ -64,12 +68,16 @@ module ActionView #:nodoc: if template = load_path.find_by_parts(template_path, format) return template # Try to find html version if the format is javascript - elsif format == :js && template = load_path["#{template_path}.html"] + elsif format == :js && html_fallback && template = load_path["#{template_path}.#{I18n.locale}.html"] + return template + elsif format == :js && html_fallback && template = load_path["#{template_path}.html"] return template end end - Template.new(original_template_path, self) + return Template.new(original_template_path, original_template_path.to_s =~ /\A\// ? "" : ".") if File.file?(original_template_path) + + raise MissingTemplate.new(self, original_template_path, format) end end end diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb index 2d8bdab100..a9b2acecd5 100644 --- a/actionpack/lib/action_view/render/rendering.rb +++ b/actionpack/lib/action_view/render/rendering.rb @@ -62,22 +62,19 @@ module ActionView end def _render_template(template, local_assigns = {}) - @_render_stack.push(template) + with_template(template) do + _evaluate_assigns_and_ivars + _set_controller_content_type(template.mime_type) if template.respond_to?(:mime_type) - _evaluate_assigns_and_ivars - _set_controller_content_type(template.mime_type) if template.respond_to?(:mime_type) - - result = template.render(self, local_assigns) do |*names| - if !instance_variable_defined?(:"@content_for_#{names.first}") && - instance_variable_defined?(:@_proc_for_layout) && (proc = @_proc_for_layout) - capture(*names, &proc) - elsif instance_variable_defined?(ivar = :"@content_for_#{names.first || :layout}") - instance_variable_get(ivar) - end + template.render(self, local_assigns) do |*names| + if !instance_variable_defined?(:"@content_for_#{names.first}") && + instance_variable_defined?(:@_proc_for_layout) && (proc = @_proc_for_layout) + capture(*names, &proc) + elsif instance_variable_defined?(ivar = :"@content_for_#{names.first || :layout}") + instance_variable_get(ivar) + end + end end - - @_render_stack.pop - result rescue Exception => e raise e if template.is_a?(InlineTemplate) || !template.filename if TemplateError === e diff --git a/actionpack/lib/action_view/template/renderable.rb b/actionpack/lib/action_view/template/renderable.rb index fde37544f3..0e8e0c4a38 100644 --- a/actionpack/lib/action_view/template/renderable.rb +++ b/actionpack/lib/action_view/template/renderable.rb @@ -1,3 +1,5 @@ +# encoding: utf-8 + module ActionView # NOTE: The template that this mixin is being included into is frozen # so you cannot set or modify any instance variables diff --git a/actionpack/lib/action_view/template/template.rb b/actionpack/lib/action_view/template/template.rb index 73e319b489..a61c46020f 100644 --- a/actionpack/lib/action_view/template/template.rb +++ b/actionpack/lib/action_view/template/template.rb @@ -50,7 +50,7 @@ module ActionView #:nodoc: def find_by_parts(name, extensions = nil, prefix = nil, partial = nil) path = prefix ? "#{prefix}/" : "" - name = name.split("/") + name = name.to_s.split("/") name[-1] = "_#{name[-1]}" if partial path << name.join("/") @@ -111,7 +111,7 @@ 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 @@ -127,13 +127,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 @@ -151,7 +158,7 @@ module ActionView #:nodoc: end def mime_type - Mime::Type.lookup_by_extension(format) if format + Mime::Type.lookup_by_extension(format) if format && defined?(::Mime) end memoize :mime_type @@ -230,7 +237,7 @@ module ActionView #:nodoc: # Returns file split into an array # [base_path, name, locale, format, extension] def split(file) - if m = file.match(/^(.*\/)?([^\.]+)\.(.*)$/) + if m = file.to_s.match(/^(.*\/)?([^\.]+)\.(.*)$/) base_path = m[1] name = m[2] extensions = m[3] @@ -242,24 +249,24 @@ module ActionView #:nodoc: format = nil extension = nil - if m = extensions.match(/^(\w+)?\.?(\w+)?\.?(\w+)?\.?/) - if valid_locale?(m[1]) && m[2] && valid_extension?(m[3]) # All three - locale = m[1] - format = m[2] - extension = m[3] - elsif m[1] && m[2] && valid_extension?(m[3]) # Multipart formats - format = "#{m[1]}.#{m[2]}" - extension = m[3] - elsif valid_locale?(m[1]) && valid_extension?(m[2]) # locale and extension - locale = m[1] - extension = m[2] - elsif valid_extension?(m[2]) # format and extension + if m = extensions.split(".") + if valid_locale?(m[0]) && m[1] && valid_extension?(m[2]) # All three + locale = m[0] format = m[1] extension = m[2] - elsif valid_extension?(m[1]) # Just extension + elsif m[0] && m[1] && valid_extension?(m[2]) # Multipart formats + format = "#{m[0]}.#{m[1]}" + extension = m[2] + elsif valid_locale?(m[0]) && valid_extension?(m[1]) # locale and extension + locale = m[0] + extension = m[1] + elsif valid_extension?(m[1]) # format and extension + format = m[0] extension = m[1] + elsif valid_extension?(m[0]) # Just extension + extension = m[0] else # No extension - format = m[1] + format = m[0] end end diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 12b60ddf3c..b07e6e5f3a 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -8,7 +8,7 @@ require 'yaml' require 'stringio' require 'test/unit' -gem 'mocha', '>= 0.9.3' +gem 'mocha', '>= 0.9.5' require 'mocha' begin @@ -33,11 +33,8 @@ ActionController::Base.session_store = nil # Register danish language for testing I18n.backend.store_translations 'da', {} -ORIGINAL_LOCALES = I18n.available_locales +I18n.backend.store_translations 'pt-BR', {} +ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures') ActionController::Base.view_paths = FIXTURE_LOAD_PATH - -def uses_mocha(test_name) - yield -end diff --git a/actionpack/test/active_record_unit.rb b/actionpack/test/active_record_unit.rb index d8d2e00dc2..9e0c66055d 100644 --- a/actionpack/test/active_record_unit.rb +++ b/actionpack/test/active_record_unit.rb @@ -51,7 +51,8 @@ class ActiveRecordTestConnector if Object.const_defined?(:ActiveRecord) defaults = { :database => ':memory:' } begin - options = defaults.merge :adapter => 'sqlite3', :timeout => 500 + adapter = defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' + options = defaults.merge :adapter => adapter, :timeout => 500 ActiveRecord::Base.establish_connection(options) ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => options } ActiveRecord::Base.connection diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb index 6a75e6050d..34f18806a2 100644 --- a/actionpack/test/activerecord/active_record_store_test.rb +++ b/actionpack/test/activerecord/active_record_store_test.rb @@ -21,6 +21,18 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest render :text => "foo: #{session[:foo].inspect}" end + def get_session_id + session[:foo] + render :text => "#{request.session_options[:id]}" + end + + def call_reset_session + session[:bar] + reset_session + session[:bar] = "baz" + head :ok + end + def rescue_action(e) raise end end @@ -33,31 +45,69 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest ActiveRecord::SessionStore.session_class.drop_table! end - def test_setting_and_getting_session_value + %w{ session sql_bypass }.each do |class_name| + define_method("test_setting_and_getting_session_value_with_#{class_name}_store") do + with_store class_name do + with_test_route_set do + get '/set_session_value' + assert_response :success + assert cookies['_session_id'] + + get '/get_session_value' + assert_response :success + assert_equal 'foo: "bar"', response.body + + get '/set_session_value', :foo => "baz" + assert_response :success + assert cookies['_session_id'] + + get '/get_session_value' + assert_response :success + assert_equal 'foo: "baz"', response.body + end + end + end + end + + def test_getting_nil_session_value + with_test_route_set do + get '/get_session_value' + assert_response :success + assert_equal 'foo: nil', response.body + 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'] + session_id = cookies['_session_id'] - get '/get_session_value' + get '/call_reset_session' assert_response :success - assert_equal 'foo: "bar"', response.body + assert_not_equal [], headers['Set-Cookie'] - get '/set_session_value', :foo => "baz" + get '/get_session_value' assert_response :success - assert cookies['_session_id'] + assert_equal 'foo: nil', response.body - get '/get_session_value' + get '/get_session_id' assert_response :success - assert_equal 'foo: "baz"', response.body + assert_not_equal session_id, response.body end end - def test_getting_nil_session_value + def test_getting_session_id with_test_route_set do - get '/get_session_value' + get '/set_session_value' assert_response :success - assert_equal 'foo: nil', response.body + assert cookies['_session_id'] + session_id = cookies['_session_id'] + + get '/get_session_id' + assert_response :success + assert_equal session_id, response.body end end @@ -125,4 +175,11 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest yield end end + + def with_store(class_name) + session_class, ActiveRecord::SessionStore.session_class = + ActiveRecord::SessionStore.session_class, "ActiveRecord::SessionStore::#{class_name.camelize}".constantize + yield + ActiveRecord::SessionStore.session_class = session_class + end end diff --git a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb index 147b270808..0a596c7ae0 100644 --- a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb +++ b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb @@ -53,7 +53,7 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase def test_rendering_partial_with_has_many_and_belongs_to_association get :render_with_has_many_and_belongs_to_association assert_template 'projects/_project' - assert_equal 'Active RecordActive Controller', @response.body + assert_equal assigns(:developer).projects.map(&:name).join, @response.body end def test_rendering_partial_with_has_many_association @@ -82,7 +82,7 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase def test_render_with_record_collection_and_spacer_template get :render_with_record_collection_and_spacer_template - assert_equal 'Active Recordonly partialActive Controller', @response.body + assert_equal assigns(:developer).projects.map(&:name).join('only partial'), @response.body end def test_rendering_partial_with_has_one_association diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index 3db1d4addf..ad17d1288b 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -78,7 +78,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 @@ -97,24 +97,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 @@ -122,17 +122,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 @@ -212,12 +212,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 @@ -255,7 +255,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 # @@ -333,7 +338,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 @@ -348,10 +353,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 @@ -375,7 +380,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 @@ -393,7 +398,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 @@ -403,7 +408,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 @@ -421,7 +426,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 @@ -431,7 +436,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 @@ -577,7 +582,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. @@ -610,8 +615,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. @@ -703,7 +708,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/caching_test.rb b/actionpack/test/controller/caching_test.rb index d743f50dff..b61a58dd09 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -109,13 +109,11 @@ class PageCachingTest < ActionController::TestCase assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html") end - uses_mocha("should_cache_ok_at_custom_path") do - def test_should_cache_ok_at_custom_path - @request.stubs(:path).returns("/index.html") - get :ok - assert_response :ok - assert File.exist?("#{FILE_STORE_PATH}/index.html") - end + def test_should_cache_ok_at_custom_path + @request.stubs(:path).returns("/index.html") + get :ok + assert_response :ok + assert File.exist?("#{FILE_STORE_PATH}/index.html") end [:ok, :no_content, :found, :not_found].each do |status| @@ -293,13 +291,11 @@ class ActionCacheTest < ActionController::TestCase ActionController::Base.use_accept_header = old_use_accept_header end - uses_mocha 'test action cache' do - def test_action_cache_with_store_options - MockTime.expects(:now).returns(12345).once - @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once - @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once - get :index - end + def test_action_cache_with_store_options + MockTime.expects(:now).returns(12345).once + @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once + @controller.expects(:write_fragment).with('hostname.com/action_caching_test', '12345.0', :expires_in => 1.hour).once + get :index end def test_action_cache_with_custom_cache_path @@ -434,6 +430,20 @@ class ActionCacheTest < ActionController::TestCase assert_equal 'application/xml', @response.content_type end + def test_correct_content_type_is_returned_for_cache_hit_on_action_with_string_key + # run it twice to cache it the first time + get :show, :format => 'xml' + get :show, :format => 'xml' + assert_equal 'application/xml', @response.content_type + end + + def test_correct_content_type_is_returned_for_cache_hit_on_action_with_string_key_from_proc + # run it twice to cache it the first time + get :edit, :id => 1, :format => 'xml' + get :edit, :id => 1, :format => 'xml' + assert_equal 'application/xml', @response.content_type + end + def test_empty_path_is_normalized @mock_controller.mock_url_for = 'http://example.org/' @mock_controller.mock_path = '/' diff --git a/actionpack/test/controller/cookie_test.rb b/actionpack/test/controller/cookie_test.rb index 5a00de50ac..c861982698 100644 --- a/actionpack/test/controller/cookie_test.rb +++ b/actionpack/test/controller/cookie_test.rb @@ -6,6 +6,10 @@ class CookieTest < ActionController::TestCase cookies["user_name"] = "david" end + def set_with_with_escapable_characters + cookies["that & guy"] = "foo & bar => baz" + end + def authenticate_for_fourteen_days cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) } end @@ -33,7 +37,7 @@ class CookieTest < ActionController::TestCase end def authenticate_with_http_only - cookies["user_name"] = { :value => "david", :http_only => true } + cookies["user_name"] = { :value => "david", :httponly => true } end def rescue_action(e) @@ -54,6 +58,12 @@ class CookieTest < ActionController::TestCase assert_equal({"user_name" => "david"}, @response.cookies) end + def test_setting_with_escapable_characters + get :set_with_with_escapable_characters + assert_equal ["that+%26+guy=foo+%26+bar+%3D%3E+baz; path=/"], @response.headers["Set-Cookie"] + assert_equal({"that & guy" => "foo & bar => baz"}, @response.cookies) + end + def test_setting_cookie_for_fourteen_days get :authenticate_for_fourteen_days assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"] diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb index 6b409c9ae2..031a10975d 100644 --- a/actionpack/test/controller/dispatcher_test.rb +++ b/actionpack/test/controller/dispatcher_test.rb @@ -1,21 +1,22 @@ require 'abstract_unit' -uses_mocha 'dispatcher tests' do - class DispatcherTest < Test::Unit::TestCase Dispatcher = ActionController::Dispatcher def setup ENV['REQUEST_METHOD'] = 'GET' + Dispatcher.middleware = ActionDispatch::MiddlewareStack.new do |middleware| + middlewares = File.expand_path(File.join(File.dirname(__FILE__), "../../lib/action_controller/dispatch/middlewares.rb")) + middleware.instance_eval(File.read(middlewares)) + end + # Clear callbacks as they are redefined by Dispatcher#define_dispatcher_callbacks Dispatcher.instance_variable_set("@prepare_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) Dispatcher.instance_variable_set("@before_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) Dispatcher.instance_variable_set("@after_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new) Dispatcher.stubs(:require_dependency) - - @dispatcher = Dispatcher.new end def teardown @@ -67,7 +68,7 @@ class DispatcherTest < Test::Unit::TestCase assert_nil a || b || c # Run callbacks - @dispatcher.send :run_callbacks, :prepare_dispatch + Dispatcher.run_prepare_callbacks assert_equal 1, a assert_equal 2, b @@ -84,7 +85,7 @@ class DispatcherTest < Test::Unit::TestCase Dispatcher.to_prepare(:unique_id) { |*args| a = b = 1 } Dispatcher.to_prepare(:unique_id) { |*args| a = 2 } - @dispatcher.send :run_callbacks, :prepare_dispatch + Dispatcher.run_prepare_callbacks assert_equal 2, a assert_equal nil, b end @@ -93,12 +94,10 @@ class DispatcherTest < Test::Unit::TestCase def dispatch(cache_classes = true) ActionController::Routing::RouteSet.any_instance.stubs(:call).returns([200, {}, 'response']) Dispatcher.define_dispatcher_callbacks(cache_classes) - @dispatcher.call({}) + Dispatcher.new.call({}) end def assert_subclasses(howmany, klass, message = klass.subclasses.inspect) assert_equal howmany, klass.subclasses.size, message end end - -end 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/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb index 59f7a403b5..00789eea38 100644 --- a/actionpack/test/controller/http_digest_authentication_test.rb +++ b/actionpack/test/controller/http_digest_authentication_test.rb @@ -5,7 +5,8 @@ class HttpDigestAuthenticationTest < ActionController::TestCase before_filter :authenticate, :only => :index before_filter :authenticate_with_request, :only => :display - USERS = { 'lifo' => 'world', 'pretty' => 'please' } + USERS = { 'lifo' => 'world', 'pretty' => 'please', + 'dhh' => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":"))} def index render :text => "Hello Secret" @@ -107,21 +108,68 @@ class HttpDigestAuthenticationTest < ActionController::TestCase assert_equal 'Definitely Maybe', @response.body end + test "authentication request with valid credential and nil session" do + @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') + + # session_id = "" in functional test, but is +nil+ in real life + @request.session.session_id = nil + get :display + + assert_response :success + assert assigns(:logged_in) + assert_equal 'Definitely Maybe', @response.body + end + + test "authentication request with request-uri that doesn't match credentials digest-uri" do + @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') + @request.env['REQUEST_URI'] = "/http_digest_authentication_test/dummy_digest/altered/uri" + get :display + + assert_response :unauthorized + assert_equal "Authentication Failed", @response.body + end + + test "authentication request with absolute uri" do + @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:uri => "http://test.host/http_digest_authentication_test/dummy_digest/display", + :username => 'pretty', :password => 'please') + @request.env['REQUEST_URI'] = "http://test.host/http_digest_authentication_test/dummy_digest/display" + get :display + + assert_response :success + assert assigns(:logged_in) + assert_equal 'Definitely Maybe', @response.body + end + + test "authentication request with password stored as ha1 digest hash" do + @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'dhh', + :password => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":")), + :password_is_ha1 => true) + get :display + + assert_response :success + assert assigns(:logged_in) + assert_equal 'Definitely Maybe', @response.body + end + private def encode_credentials(options) - options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b") + options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b", :password_is_ha1 => false) password = options.delete(:password) - # Perform unautheticated get to retrieve digest parameters to use on subsequent request + # Set in /initializers/session_store.rb. Used as secret in generating nonce + # to prevent tampering of timestamp + ActionController::Base.session_options[:secret] = "session_options_secret" + + # Perform unauthenticated GET to retrieve digest parameters to use on subsequent request get :index assert_response :unauthorized credentials = decode_credentials(@response.headers['WWW-Authenticate']) credentials.merge!(options) - credentials.merge!(:uri => "http://#{@request.host}#{@request.env['REQUEST_URI']}") - ActionController::HttpAuthentication::Digest.encode_credentials("GET", credentials, password) + credentials.reverse_merge!(:uri => "#{@request.env['REQUEST_URI']}") + ActionController::HttpAuthentication::Digest.encode_credentials("GET", credentials, password, options[:password_is_ha1]) end def decode_credentials(header) diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 4f07cbee47..e39a934c24 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -1,10 +1,8 @@ require 'abstract_unit' -uses_mocha 'integration' do - class SessionTest < Test::Unit::TestCase StubApp = lambda { |env| - [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, "Hello, World!"] + [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, ["Hello, World!"]] } def setup @@ -266,6 +264,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest assert_response :success assert_response :ok assert_equal({}, cookies) + assert_equal "OK", body assert_equal "OK", response.body assert_kind_of HTML::Document, html_document assert_equal 1, request_count @@ -281,6 +280,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest assert_response :success assert_response :created assert_equal({}, cookies) + assert_equal "Created", body assert_equal "Created", response.body assert_kind_of HTML::Document, html_document assert_equal 1, request_count @@ -296,7 +296,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest assert_equal "Gone", status_message assert_response 410 assert_response :gone - assert_equal ["cookie_1=; path=/", "cookie_3=chocolate; path=/"], headers["Set-Cookie"] + assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"] assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies) assert_equal "Gone", response.body end @@ -360,6 +360,18 @@ class IntegrationProcessTest < ActionController::IntegrationTest end end + def test_head + with_test_route_set do + head '/get' + assert_equal 200, status + assert_equal "", body + + head '/post' + assert_equal 201, status + assert_equal "", body + end + end + private def with_test_route_set with_routing do |set| @@ -377,9 +389,9 @@ class MetalTest < ActionController::IntegrationTest class Poller def self.call(env) if env["PATH_INFO"] =~ /^\/success/ - [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, "Hello World!"] + [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, ["Hello World!"]] else - [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, ''] + [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []] end end end @@ -403,5 +415,3 @@ class MetalTest < ActionController::IntegrationTest assert_equal '', response.body end end - -end diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index 09283eddc9..f2721e274d 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -80,10 +80,21 @@ 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 +class PrependsViewPathController < LayoutTest + def hello + prepend_view_path File.dirname(__FILE__) + '/../fixtures/layout_tests/alt/' + render :layout => 'alt' + end +end + class OnlyLayoutController < LayoutTest layout 'item', :only => "hello" end @@ -163,6 +174,20 @@ class LayoutSetInResponseTest < ActionController::TestCase ensure ActionController::Base.exempt_from_layout.delete(/\.rhtml$/) end + + def test_layout_is_picked_from_the_controller_instances_view_path + pending do + @controller = PrependsViewPathController.new + get :hello + assert_equal 'layouts/alt', @response.layout + end + 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 f40a2e04d6..1c81989d9b 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -471,7 +471,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/polymorphic_routes_test.rb b/actionpack/test/controller/polymorphic_routes_test.rb index 09c7f74617..146d703619 100644 --- a/actionpack/test/controller/polymorphic_routes_test.rb +++ b/actionpack/test/controller/polymorphic_routes_test.rb @@ -18,193 +18,276 @@ class Tag < Article def response_id; 1 end end +class Tax + attr_reader :id + def save; @id = 1 end + def new_record?; @id.nil? end + def name + model = self.class.name.downcase + @id.nil? ? "new #{model}" : "#{model} ##{@id}" + end +end + +class Fax < Tax + def store_id; 1 end +end + # TODO: test nested models class Response::Nested < Response; end -uses_mocha 'polymorphic URL helpers' do - class PolymorphicRoutesTest < ActiveSupport::TestCase - include ActionController::PolymorphicRoutes +class PolymorphicRoutesTest < ActiveSupport::TestCase + include ActionController::PolymorphicRoutes - def setup - @article = Article.new - @response = Response.new - end - - def test_with_record - @article.save - expects(:article_url).with(@article) - polymorphic_url(@article) - end + def setup + @article = Article.new + @response = Response.new + @tax = Tax.new + @fax = Fax.new + end - def test_with_new_record - expects(:articles_url).with() - @article.expects(:new_record?).returns(true) - polymorphic_url(@article) - end + def test_with_record + @article.save + expects(:article_url).with(@article) + polymorphic_url(@article) + end - def test_with_record_and_action - expects(:new_article_url).with() - @article.expects(:new_record?).never - polymorphic_url(@article, :action => 'new') - end + def test_with_new_record + expects(:articles_url).with() + @article.expects(:new_record?).returns(true) + polymorphic_url(@article) + end - def test_url_helper_prefixed_with_new - expects(:new_article_url).with() - new_polymorphic_url(@article) - end + def test_with_record_and_action + expects(:new_article_url).with() + @article.expects(:new_record?).never + polymorphic_url(@article, :action => 'new') + end - def test_url_helper_prefixed_with_edit - @article.save - expects(:edit_article_url).with(@article) - edit_polymorphic_url(@article) - end + def test_url_helper_prefixed_with_new + expects(:new_article_url).with() + new_polymorphic_url(@article) + end - def test_url_helper_prefixed_with_edit_with_url_options - @article.save - expects(:edit_article_url).with(@article, :param1 => '10') - edit_polymorphic_url(@article, :param1 => '10') - end + def test_url_helper_prefixed_with_edit + @article.save + expects(:edit_article_url).with(@article) + edit_polymorphic_url(@article) + end - def test_url_helper_with_url_options - @article.save - expects(:article_url).with(@article, :param1 => '10') - polymorphic_url(@article, :param1 => '10') - end + def test_url_helper_prefixed_with_edit_with_url_options + @article.save + expects(:edit_article_url).with(@article, :param1 => '10') + edit_polymorphic_url(@article, :param1 => '10') + end - def test_formatted_url_helper_is_deprecated - expects(:articles_url).with(:format => :pdf) - assert_deprecated do - formatted_polymorphic_url([@article, :pdf]) - end - end + def test_url_helper_with_url_options + @article.save + expects(:article_url).with(@article, :param1 => '10') + polymorphic_url(@article, :param1 => '10') + end - def test_format_option - @article.save - expects(:article_url).with(@article, :format => :pdf) - polymorphic_url(@article, :format => :pdf) + def test_formatted_url_helper_is_deprecated + expects(:articles_url).with(:format => :pdf) + assert_deprecated do + formatted_polymorphic_url([@article, :pdf]) end + end - def test_format_option_with_url_options - @article.save - expects(:article_url).with(@article, :format => :pdf, :param1 => '10') - polymorphic_url(@article, :format => :pdf, :param1 => '10') - end + def test_format_option + @article.save + expects(:article_url).with(@article, :format => :pdf) + polymorphic_url(@article, :format => :pdf) + end - def test_id_and_format_option - @article.save - expects(:article_url).with(:id => @article, :format => :pdf) - polymorphic_url(:id => @article, :format => :pdf) - end + def test_format_option_with_url_options + @article.save + expects(:article_url).with(@article, :format => :pdf, :param1 => '10') + polymorphic_url(@article, :format => :pdf, :param1 => '10') + end - def test_with_nested - @response.save - expects(:article_response_url).with(@article, @response) - polymorphic_url([@article, @response]) - end + def test_id_and_format_option + @article.save + expects(:article_url).with(:id => @article, :format => :pdf) + polymorphic_url(:id => @article, :format => :pdf) + end - def test_with_nested_unsaved - expects(:article_responses_url).with(@article) - polymorphic_url([@article, @response]) - end + def test_with_nested + @response.save + expects(:article_response_url).with(@article, @response) + polymorphic_url([@article, @response]) + end - def test_new_with_array_and_namespace - expects(:new_admin_article_url).with() - polymorphic_url([:admin, @article], :action => 'new') - end + def test_with_nested_unsaved + expects(:article_responses_url).with(@article) + polymorphic_url([@article, @response]) + end - def test_unsaved_with_array_and_namespace - expects(:admin_articles_url).with() - polymorphic_url([:admin, @article]) - end + def test_new_with_array_and_namespace + expects(:new_admin_article_url).with() + polymorphic_url([:admin, @article], :action => 'new') + end - def test_nested_unsaved_with_array_and_namespace - @article.save - expects(:admin_article_url).with(@article) - polymorphic_url([:admin, @article]) - expects(:admin_article_responses_url).with(@article) - polymorphic_url([:admin, @article, @response]) - end + def test_unsaved_with_array_and_namespace + expects(:admin_articles_url).with() + polymorphic_url([:admin, @article]) + end - def test_nested_with_array_and_namespace - @response.save - expects(:admin_article_response_url).with(@article, @response) - polymorphic_url([:admin, @article, @response]) + def test_nested_unsaved_with_array_and_namespace + @article.save + expects(:admin_article_url).with(@article) + polymorphic_url([:admin, @article]) + expects(:admin_article_responses_url).with(@article) + polymorphic_url([:admin, @article, @response]) + end - # a ridiculously long named route tests correct ordering of namespaces and nesting: - @tag = Tag.new - @tag.save - expects(:site_admin_article_response_tag_url).with(@article, @response, @tag) - polymorphic_url([:site, :admin, @article, @response, @tag]) - end + def test_nested_with_array_and_namespace + @response.save + expects(:admin_article_response_url).with(@article, @response) + polymorphic_url([:admin, @article, @response]) - def test_nesting_with_array_ending_in_singleton_resource - expects(:article_response_url).with(@article) - polymorphic_url([@article, :response]) - end + # a ridiculously long named route tests correct ordering of namespaces and nesting: + @tag = Tag.new + @tag.save + expects(:site_admin_article_response_tag_url).with(@article, @response, @tag) + polymorphic_url([:site, :admin, @article, @response, @tag]) + end - def test_nesting_with_array_containing_singleton_resource - @tag = Tag.new - @tag.save - expects(:article_response_tag_url).with(@article, @tag) - polymorphic_url([@article, :response, @tag]) - end + def test_nesting_with_array_ending_in_singleton_resource + expects(:article_response_url).with(@article) + polymorphic_url([@article, :response]) + end - def test_nesting_with_array_containing_namespace_and_singleton_resource - @tag = Tag.new - @tag.save - expects(:admin_article_response_tag_url).with(@article, @tag) - polymorphic_url([:admin, @article, :response, @tag]) - end + def test_nesting_with_array_containing_singleton_resource + @tag = Tag.new + @tag.save + expects(:article_response_tag_url).with(@article, @tag) + polymorphic_url([@article, :response, @tag]) + end - def test_nesting_with_array_containing_singleton_resource_and_format - @tag = Tag.new - @tag.save - expects(:article_response_tag_url).with(@article, @tag, :format => :pdf) - polymorphic_url([@article, :response, @tag], :format => :pdf) - end + def test_nesting_with_array_containing_namespace_and_singleton_resource + @tag = Tag.new + @tag.save + expects(:admin_article_response_tag_url).with(@article, @tag) + polymorphic_url([:admin, @article, :response, @tag]) + end - def test_nesting_with_array_containing_singleton_resource_and_format_option - @tag = Tag.new - @tag.save - expects(:article_response_tag_url).with(@article, @tag, :format => :pdf) - polymorphic_url([@article, :response, @tag], :format => :pdf) - end + def test_nesting_with_array_containing_singleton_resource_and_format + @tag = Tag.new + @tag.save + expects(:article_response_tag_url).with(@article, @tag, :format => :pdf) + polymorphic_url([@article, :response, @tag], :format => :pdf) + end - def test_nesting_with_array_containing_nil - expects(:article_response_url).with(@article) - polymorphic_url([@article, nil, :response]) - end + def test_nesting_with_array_containing_singleton_resource_and_format_option + @tag = Tag.new + @tag.save + expects(:article_response_tag_url).with(@article, @tag, :format => :pdf) + polymorphic_url([@article, :response, @tag], :format => :pdf) + end - def test_with_array_containing_single_object - @article.save - expects(:article_url).with(@article) - polymorphic_url([nil, @article]) - end + def test_nesting_with_array_containing_nil + expects(:article_response_url).with(@article) + polymorphic_url([@article, nil, :response]) + end - def test_with_array_containing_single_name - @article.save - expects(:articles_url) - polymorphic_url([:articles]) - end + def test_with_array_containing_single_object + @article.save + expects(:article_url).with(@article) + polymorphic_url([nil, @article]) + end - # TODO: Needs to be updated to correctly know about whether the object is in a hash or not - def xtest_with_hash - expects(:article_url).with(@article) - @article.save - polymorphic_url(:id => @article) - end + def test_with_array_containing_single_name + @article.save + expects(:articles_url) + polymorphic_url([:articles]) + end - def test_polymorphic_path_accepts_options - expects(:new_article_path).with() - polymorphic_path(@article, :action => :new) - end + # TODO: Needs to be updated to correctly know about whether the object is in a hash or not + def xtest_with_hash + expects(:article_url).with(@article) + @article.save + polymorphic_url(:id => @article) + end + + def test_polymorphic_path_accepts_options + expects(:new_article_path).with() + polymorphic_path(@article, :action => :new) + end - def test_polymorphic_path_does_not_modify_arguments - expects(:admin_article_responses_url).with(@article) - path = [:admin, @article, @response] - assert_no_difference 'path.size' do - polymorphic_url(path) - end + def test_polymorphic_path_does_not_modify_arguments + expects(:admin_article_responses_url).with(@article) + path = [:admin, @article, @response] + assert_no_difference 'path.size' do + polymorphic_url(path) end end + + # Tests for names where .plural.singular doesn't round-trip + def test_with_irregular_plural_record + @tax.save + expects(:taxis_url).with(@tax) + polymorphic_url(@tax) + end + + def test_with_irregular_plural_new_record + expects(:taxes_url).with() + @tax.expects(:new_record?).returns(true) + polymorphic_url(@tax) + end + + def test_with_irregular_plural_record_and_action + expects(:new_taxis_url).with() + @tax.expects(:new_record?).never + polymorphic_url(@tax, :action => 'new') + end + + def test_irregular_plural_url_helper_prefixed_with_new + expects(:new_taxis_url).with() + new_polymorphic_url(@tax) + end + + def test_irregular_plural_url_helper_prefixed_with_edit + @tax.save + expects(:edit_taxis_url).with(@tax) + edit_polymorphic_url(@tax) + end + + def test_with_nested_irregular_plurals + @fax.save + expects(:taxis_faxis_url).with(@tax, @fax) + polymorphic_url([@tax, @fax]) + end + + def test_with_nested_unsaved_irregular_plurals + expects(:taxis_faxes_url).with(@tax) + polymorphic_url([@tax, @fax]) + end + + def test_new_with_irregular_plural_array_and_namespace + expects(:new_admin_taxis_url).with() + polymorphic_url([:admin, @tax], :action => 'new') + end + + def test_unsaved_with_irregular_plural_array_and_namespace + expects(:admin_taxes_url).with() + polymorphic_url([:admin, @tax]) + end + + def test_nesting_with_irregular_plurals_and_array_ending_in_singleton_resource + expects(:taxis_faxis_url).with(@tax) + polymorphic_url([@tax, :faxis]) + end + + def test_with_array_containing_single_irregular_plural_object + @tax.save + expects(:taxis_url).with(@tax) + polymorphic_url([nil, @tax]) + end + + def test_with_array_containing_single_name_irregular_plural + @tax.save + expects(:taxes_url) + polymorphic_url([:taxes]) + 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 dde49cd136..9a34bcebe6 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' @@ -124,6 +157,11 @@ class TestController < ActionController::Base render :file => 'test/dot.directory/render_file_with_ivar' end + def render_file_using_pathname + @secret = 'in the sauce' + render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar.erb') + end + def render_file_from_template @secret = 'in the sauce' @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) @@ -642,6 +680,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 @@ -686,6 +732,8 @@ class TestController < ActionController::Base "layouts/standard" 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 @@ -805,6 +853,11 @@ class RenderTest < ActionController::TestCase assert_equal "The secret is in the sauce\n", @response.body end + def test_render_file_using_pathname + get :render_file_using_pathname + assert_equal "The secret is in the sauce\n", @response.body + end + def test_render_file_with_locals get :render_file_with_locals assert_equal "The secret is in the sauce\n", @response.body @@ -881,11 +934,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 @@ -1016,8 +1069,15 @@ class RenderTest < ActionController::TestCase def test_should_implicitly_render_html_template_from_xhr_request pending do - 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 + end + + def test_should_implicitly_render_js_template_without_layout + pending do + get :render_implicit_js_template_without_layout, :format => :js + assert_no_match %r{<html>}, @response.body end end @@ -1109,7 +1169,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 @@ -1134,15 +1194,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 @@ -1423,6 +1483,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 @@ -1441,7 +1511,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 @@ -1457,6 +1527,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 @@ -1547,6 +1646,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/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb new file mode 100644 index 0000000000..81551b4ba7 --- /dev/null +++ b/actionpack/test/controller/request/test_request_test.rb @@ -0,0 +1,35 @@ +require 'abstract_unit' +require 'stringio' + +class ActionController::TestRequestTest < ActiveSupport::TestCase + + def setup + @request = ActionController::TestRequest.new + end + + def test_test_request_has_session_options_initialized + assert @request.session_options + end + + Rack::Session::Abstract::ID::DEFAULT_OPTIONS.each_key do |option| + test "test_rack_default_session_options_#{option}_exists_in_session_options_and_is_default" do + assert_equal(Rack::Session::Abstract::ID::DEFAULT_OPTIONS[option], + @request.session_options[option], + "Missing rack session default option #{option} in request.session_options") + end + test "test_rack_default_session_options_#{option}_exists_in_session_options" do + assert(@request.session_options.has_key?(option), + "Missing rack session option #{option} in request.session_options") + end + end + + def test_session_id_exists_by_default + assert_not_nil(@request.session_options[:id]) + end + + def test_session_id_different_on_each_call + prev_id = + assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id]) + end + +end
\ No newline at end of file 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/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index 744ca9286c..741b01caa8 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -1,7 +1,5 @@ require 'abstract_unit' -uses_mocha 'rescue' do - class RescueController < ActionController::Base class NotAuthorized < StandardError end @@ -202,6 +200,24 @@ class RescueControllerTest < ActionController::TestCase end end + def test_rescue_action_in_public_with_localized_error_file + # Change locale + old_locale = I18n.locale + I18n.locale = :da + + with_rails_root FIXTURE_PUBLIC do + with_all_requests_local false do + get :raises + end + end + + assert_response :internal_server_error + body = File.read("#{FIXTURE_PUBLIC}/public/500.da.html") + assert_equal body, @response.body + ensure + I18n.locale = old_locale + end + def test_rescue_action_in_public_with_error_file with_rails_root FIXTURE_PUBLIC do with_all_requests_local false do @@ -521,4 +537,3 @@ class ControllerInheritanceRescueControllerTest < ActionController::TestCase assert_response :created end end -end # uses_mocha diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 8dedeb23f6..c807e71cd7 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 @@ -175,6 +175,24 @@ class ResourcesTest < ActionController::TestCase end end + def test_with_collection_actions_and_name_prefix_and_member_action_with_same_name + actions = { 'a' => :get } + + with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions, :member => actions do + assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| + actions.each do |action, method| + assert_recognizes(options.merge(:action => action), :path => "/threads/1/messages/#{action}", :method => method) + end + end + + assert_restful_named_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| + actions.keys.each do |action| + assert_named_route "/threads/1/messages/#{action}", "#{action}_thread_messages_path", :action => action + end + end + end + end + def test_with_collection_action_and_name_prefix_and_formatted actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } @@ -209,6 +227,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 +351,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 +432,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 +637,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 +650,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 +660,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 +804,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 @@ -942,19 +1004,6 @@ class ResourcesTest < ActionController::TestCase end end - def test_nested_resource_inherits_only_show_action - with_routing do |set| - set.draw do |map| - map.resources :products, :only => :show do |product| - product.resources :images - end - end - - assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images') - assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images') - end - end - def test_nested_resource_has_only_show_and_member_action with_routing do |set| set.draw do |map| @@ -971,7 +1020,7 @@ class ResourcesTest < ActionController::TestCase end end - def test_nested_resource_ignores_only_option + def test_nested_resource_does_not_inherit_only_option with_routing do |set| set.draw do |map| map.resources :products, :only => :show do |product| @@ -984,7 +1033,20 @@ class ResourcesTest < ActionController::TestCase end end - def test_nested_resource_ignores_except_option + def test_nested_resource_does_not_inherit_only_option_by_default + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :show do |product| + product.resources :images + end + end + + assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update, :destory], [], 'products/1/images') + assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update, :destroy], [], 'products/1/images') + end + end + + def test_nested_resource_does_not_inherit_except_option with_routing do |set| set.draw do |map| map.resources :products, :except => :show do |product| @@ -997,6 +1059,19 @@ class ResourcesTest < ActionController::TestCase end end + def test_nested_resource_does_not_inherit_except_option_by_default + with_routing do |set| + set.draw do |map| + map.resources :products, :except => :show do |product| + product.resources :images + end + end + + assert_resource_allowed_routes('images', { :product_id => '1' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update, :destroy], [], 'products/1/images') + assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' }, { :id => '2' }, [:index, :new, :create, :show, :edit, :update, :destroy], [], 'products/1/images') + end + end + def test_default_singleton_restful_route_uses_get with_routing do |set| set.draw do |map| @@ -1053,7 +1128,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}" @@ -1117,10 +1192,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 b981119e1e..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 @@ -340,6 +340,30 @@ class ControllerSegmentTest < Test::Unit::TestCase end end +class PathSegmentTest < Test::Unit::TestCase + def segment(options = {}) + unless @segment + @segment = ROUTING::PathSegment.new(:path, options) + end + @segment + end + + def test_regexp_chunk_should_return_string + segment = segment(:regexp => /[a-z]+/) + assert_kind_of String, segment.regexp_chunk + end + + def test_regexp_chunk_should_be_wrapped_with_parenthesis + segment = segment(:regexp => /[a-z]+/) + assert_equal "([a-z]+)", segment.regexp_chunk + end + + def test_regexp_chunk_should_respect_options + segment = segment(:regexp => /[a-z]+/i) + assert_equal "((?i-mx:[a-z]+))", segment.regexp_chunk + end +end + class RouteBuilderTest < Test::Unit::TestCase def builder @builder ||= ROUTING::RouteBuilder.new @@ -470,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 @@ -691,1635 +715,1656 @@ class RoutingTest < Test::Unit::TestCase end end -uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do - class MockController - attr_accessor :routes - - def initialize(routes) - self.routes = routes - end +class MockController + attr_accessor :routes - def url_for(options) - only_path = options.delete(:only_path) + def initialize(routes) + self.routes = routes + end - port = options.delete(:port) || 80 - port_string = port == 80 ? '' : ":#{port}" + def url_for(options) + only_path = options.delete(:only_path) - protocol = options.delete(:protocol) || "http" - host = options.delete(:host) || "test.host" - anchor = "##{options.delete(:anchor)}" if options.key?(:anchor) + port = options.delete(:port) || 80 + port_string = port == 80 ? '' : ":#{port}" - path = routes.generate(options) + protocol = options.delete(:protocol) || "http" + host = options.delete(:host) || "test.host" + anchor = "##{options.delete(:anchor)}" if options.key?(:anchor) - only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}" - end + path = routes.generate(options) - def request - @request ||= ActionController::TestRequest.new - end + only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}" end - class LegacyRouteSetTests < Test::Unit::TestCase - attr_reader :rs + def request + @request ||= ActionController::TestRequest.new + end +end - def setup - # These tests assume optimisation is on, so re-enable it. - ActionController::Base.optimise_named_routes = true +class LegacyRouteSetTests < Test::Unit::TestCase + attr_reader :rs - @rs = ::ActionController::Routing::RouteSet.new + def setup + # These tests assume optimisation is on, so re-enable it. + ActionController::Base.optimise_named_routes = true + + @rs = ::ActionController::Routing::RouteSet.new + + ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed) + end + + def teardown + @rs.clear! + end + + def test_default_setup + @rs.draw {|m| m.connect ':controller/:action/:id' } + assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content")) + assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list")) + assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10")) + + assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10")) + + assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10) + + assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) + assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'}) + + assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) + assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) + end + + def test_ignores_leading_slash + @rs.clear! + @rs.draw {|m| m.connect '/:controller/:action/:id'} + test_default_setup + end + + def test_time_recognition + # We create many routes to make situation more realistic + @rs = ::ActionController::Routing::RouteSet.new + @rs.draw { |map| + map.frontpage '', :controller => 'search', :action => 'new' + map.resources :videos do |video| + video.resources :comments + video.resource :file, :controller => 'video_file' + video.resource :share, :controller => 'video_shares' + video.resource :abuse, :controller => 'video_abuses' + end + map.resources :abuses, :controller => 'video_abuses' + map.resources :video_uploads + map.resources :video_visits + + map.resources :users do |user| + user.resource :settings + user.resources :videos + end + map.resources :channels do |channel| + channel.resources :videos, :controller => 'channel_videos' + end + map.resource :session + map.resource :lost_password + map.search 'search', :controller => 'search' + map.resources :pages + map.connect ':controller/:action/:id' + } + n = 1000 + if RunTimeTests + GC.start + rectime = Benchmark.realtime do + n.times do + rs.recognize_path("/videos/1234567", {:method => :get}) + rs.recognize_path("/videos/1234567/abuse", {:method => :get}) + rs.recognize_path("/users/1234567/settings", {:method => :get}) + rs.recognize_path("/channels/1234567", {:method => :get}) + rs.recognize_path("/session/new", {:method => :get}) + rs.recognize_path("/admin/user/show/10", {:method => :get}) + end + end + puts "\n\nRecognition (#{rs.routes.size} routes):" + per_url = rectime / (n * 6) + puts "#{per_url * 1000} ms/url" + puts "#{1 / per_url} url/s\n\n" + end + end + + def test_time_generation + n = 5000 + if RunTimeTests + GC.start + pairs = [ + [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}], + [{:controller => 'content'}, {:controller => 'content', :action => 'index'}], + [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}], + [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}], + [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}], + [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}], + [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}], + [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}], + ] + p = nil + gentime = Benchmark.realtime do + n.times do + pairs.each {|(a, b)| rs.generate(a, b)} + end + end - ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed) + puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)" + per_url = gentime / (n * 8) + puts "#{per_url * 1000} ms/url" + puts "#{1 / per_url} url/s\n\n" end - - def teardown - @rs.clear! - end - - def test_default_setup - @rs.draw {|m| m.connect ':controller/:action/:id' } - assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content")) - assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list")) - assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10")) - - assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10")) + end - assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10) + def test_route_with_colon_first + rs.draw do |map| + map.connect '/:controller/:action/:id', :action => 'index', :id => nil + map.connect ':url', :controller => 'tiny_url', :action => 'translate' + end + end - assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) - assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'}) + def test_route_with_regexp_for_controller + rs.draw do |map| + map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/ + map.connect ':controller/:action/:id' + end + assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"}, + rs.recognize_path("/admin/user/foo")) + assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo")) + assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index") + assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo") + end - assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) - assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) + def test_route_with_regexp_and_captures_for_controller + rs.draw do |map| + map.connect ':controller/:action/:id', :controller => /admin\/(accounts|users)/ 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_raise(ActionController::RoutingError) { rs.recognize_path("/admin/products") } + end - def test_ignores_leading_slash - @rs.clear! - @rs.draw {|m| m.connect '/:controller/:action/:id'} - test_default_setup + def test_route_with_regexp_and_dot + rs.draw do |map| + map.connect ':controller/:action/:file', + :controller => /admin|user/, + :action => /upload|download/, + :defaults => {:file => nil}, + :requirements => {:file => %r{[^/]+(\.[^/]+)?}} end + # Without a file extension + assert_equal '/user/download/file', + rs.generate(:controller => "user", :action => "download", :file => "file") + assert_equal( + {:controller => "user", :action => "download", :file => "file"}, + rs.recognize_path("/user/download/file")) - def test_time_recognition - # We create many routes to make situation more realistic - @rs = ::ActionController::Routing::RouteSet.new - @rs.draw { |map| - map.frontpage '', :controller => 'search', :action => 'new' - map.resources :videos do |video| - video.resources :comments - video.resource :file, :controller => 'video_file' - video.resource :share, :controller => 'video_shares' - video.resource :abuse, :controller => 'video_abuses' - end - map.resources :abuses, :controller => 'video_abuses' - map.resources :video_uploads - map.resources :video_visits + # Now, let's try a file with an extension, really a dot (.) + assert_equal '/user/download/file.jpg', + rs.generate( + :controller => "user", :action => "download", :file => "file.jpg") + assert_equal( + {:controller => "user", :action => "download", :file => "file.jpg"}, + rs.recognize_path("/user/download/file.jpg")) + end - map.resources :users do |user| - user.resource :settings - user.resources :videos - end - map.resources :channels do |channel| - channel.resources :videos, :controller => 'channel_videos' - end - map.resource :session - map.resource :lost_password - map.search 'search', :controller => 'search' - map.resources :pages - map.connect ':controller/:action/:id' - } - n = 1000 - if RunTimeTests - GC.start - rectime = Benchmark.realtime do - n.times do - rs.recognize_path("/videos/1234567", {:method => :get}) - rs.recognize_path("/videos/1234567/abuse", {:method => :get}) - rs.recognize_path("/users/1234567/settings", {:method => :get}) - rs.recognize_path("/channels/1234567", {:method => :get}) - rs.recognize_path("/session/new", {:method => :get}) - rs.recognize_path("/admin/user/show/10", {:method => :get}) - end - end - puts "\n\nRecognition (#{rs.routes.size} routes):" - per_url = rectime / (n * 6) - puts "#{per_url * 1000} ms/url" - puts "#{1 / per_url} url/s\n\n" - end - end + def test_basic_named_route + rs.add_named_route :home, '', :controller => 'content', :action => 'list' + x = setup_for_named_route + assert_equal("http://test.host/", + x.send(:home_url)) + end - def test_time_generation - n = 5000 - if RunTimeTests - GC.start - pairs = [ - [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}], - [{:controller => 'content'}, {:controller => 'content', :action => 'index'}], - [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}], - [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}], - [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}], - [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}], - [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}], - [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}], - ] - p = nil - gentime = Benchmark.realtime do - n.times do - pairs.each {|(a, b)| rs.generate(a, b)} - end - end + def test_basic_named_route_with_relative_url_root + rs.add_named_route :home, '', :controller => 'content', :action => 'list' + x = setup_for_named_route + ActionController::Base.relative_url_root = "/foo" + assert_equal("http://test.host/foo/", + x.send(:home_url)) + assert_equal "/foo/", x.send(:home_path) + ActionController::Base.relative_url_root = nil + end - puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)" - per_url = gentime / (n * 8) - puts "#{per_url * 1000} ms/url" - puts "#{1 / per_url} url/s\n\n" - end - end + def test_named_route_with_option + rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page' + x = setup_for_named_route + assert_equal("http://test.host/page/new%20stuff", + x.send(:page_url, :title => 'new stuff')) + end - def test_route_with_colon_first - rs.draw do |map| - map.connect '/:controller/:action/:id', :action => 'index', :id => nil - map.connect ':url', :controller => 'tiny_url', :action => 'translate' - end - end + def test_named_route_with_default + rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage' + x = setup_for_named_route + assert_equal("http://test.host/page/AboutRails", + x.send(:page_url, :title => "AboutRails")) - def test_route_with_regexp_for_controller - rs.draw do |map| - map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/ - map.connect ':controller/:action/:id' - end - assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"}, - rs.recognize_path("/admin/user/foo")) - assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo")) - assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index") - assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo") - end + end - def test_route_with_regexp_and_dot - rs.draw do |map| - map.connect ':controller/:action/:file', - :controller => /admin|user/, - :action => /upload|download/, - :defaults => {:file => nil}, - :requirements => {:file => %r{[^/]+(\.[^/]+)?}} - end - # Without a file extension - assert_equal '/user/download/file', - rs.generate(:controller => "user", :action => "download", :file => "file") - assert_equal( - {:controller => "user", :action => "download", :file => "file"}, - rs.recognize_path("/user/download/file")) + def test_named_route_with_name_prefix + rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_' + x = setup_for_named_route + assert_equal("http://test.host/page", + x.send(:my_page_url)) + end - # Now, let's try a file with an extension, really a dot (.) - assert_equal '/user/download/file.jpg', - rs.generate( - :controller => "user", :action => "download", :file => "file.jpg") - assert_equal( - {:controller => "user", :action => "download", :file => "file.jpg"}, - rs.recognize_path("/user/download/file.jpg")) - end + def test_named_route_with_path_prefix + rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my' + x = setup_for_named_route + assert_equal("http://test.host/my/page", + x.send(:page_url)) + end - def test_basic_named_route - rs.add_named_route :home, '', :controller => 'content', :action => 'list' - x = setup_for_named_route - assert_equal("http://test.host/", - x.send(:home_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_basic_named_route_with_relative_url_root - rs.add_named_route :home, '', :controller => 'content', :action => 'list' - x = setup_for_named_route - ActionController::Base.relative_url_root = "/foo" - assert_equal("http://test.host/foo/", - x.send(:home_url)) - assert_equal "/foo/", x.send(:home_path) - ActionController::Base.relative_url_root = nil - 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 + assert_equal("http://test.host/admin/user", + x.send(:users_url)) + end - def test_named_route_with_option - rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page' - x = setup_for_named_route - assert_equal("http://test.host/page/new%20stuff", - x.send(:page_url, :title => 'new stuff')) - end + def test_optimised_named_route_call_never_uses_url_for + rs.add_named_route :users, 'admin/user', :controller => '/admin/user', :action => 'index' + rs.add_named_route :user, 'admin/user/:id', :controller=>'/admin/user', :action=>'show' + x = setup_for_named_route + x.expects(:url_for).never + x.send(:users_url) + x.send(:users_path) + x.send(:user_url, 2, :foo=>"bar") + x.send(:user_path, 3, :bar=>"foo") + end - def test_named_route_with_default - rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage' - x = setup_for_named_route - assert_equal("http://test.host/page/AboutRails", - x.send(:page_url, :title => "AboutRails")) + def test_optimised_named_route_with_host + rs.add_named_route :pages, 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com' + x = setup_for_named_route + x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once + x.send(:pages_url) + end - end + def setup_for_named_route + klass = Class.new(MockController) + rs.install_helpers(klass) + klass.new(rs) + end - def test_named_route_with_name_prefix - rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_' - x = setup_for_named_route - assert_equal("http://test.host/page", - x.send(:my_page_url)) + def test_named_route_without_hash + rs.draw do |map| + map.normal ':controller/:action/:id' end + end - def test_named_route_with_path_prefix - rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my' - x = setup_for_named_route - assert_equal("http://test.host/my/page", - x.send(:page_url)) + def test_named_route_root + rs.draw do |map| + map.root :controller => "hello" end + x = setup_for_named_route + assert_equal("http://test.host/", x.send(:root_url)) + assert_equal("/", x.send(:root_path)) + 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 - assert_equal("http://test.host/admin/user", - x.send(:users_url)) + def test_named_route_with_regexps + rs.draw do |map| + map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show', + :year => /\d+/, :month => /\d+/, :day => /\d+/ + map.connect ':controller/:action/:id' end + x = setup_for_named_route + # assert_equal( + # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false}, + # x.send(:article_url, :title => 'hi') + # ) + assert_equal( + "http://test.host/page/2005/6/10/hi", + x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6) + ) + end - def test_optimised_named_route_call_never_uses_url_for - rs.add_named_route :users, 'admin/user', :controller => '/admin/user', :action => 'index' - rs.add_named_route :user, 'admin/user/:id', :controller=>'/admin/user', :action=>'show' - x = setup_for_named_route - x.expects(:url_for).never - x.send(:users_url) - x.send(:users_path) - x.send(:user_url, 2, :foo=>"bar") - x.send(:user_path, 3, :bar=>"foo") - end + def test_changing_controller + @rs.draw {|m| m.connect ':controller/:action/:id' } - def test_optimised_named_route_with_host - rs.add_named_route :pages, 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com' - x = setup_for_named_route - x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once - x.send(:pages_url) - end + assert_equal '/admin/stuff/show/10', rs.generate( + {:controller => 'stuff', :action => 'show', :id => 10}, + {:controller => 'admin/user', :action => 'index'} + ) + end - def setup_for_named_route - klass = Class.new(MockController) - rs.install_helpers(klass) - klass.new(rs) + def test_paths_escaped + rs.draw do |map| + map.path 'file/*path', :controller => 'content', :action => 'show_file' + map.connect ':controller/:action/:id' end - def test_named_route_without_hash - rs.draw do |map| - map.normal ':controller/:action/:id' - end - end + # No + to space in URI escaping, only for query params. + results = rs.recognize_path "/file/hello+world/how+are+you%3F" + assert results, "Recognition should have succeeded" + assert_equal ['hello+world', 'how+are+you?'], results[:path] - def test_named_route_root - rs.draw do |map| - map.root :controller => "hello" - end - x = setup_for_named_route - assert_equal("http://test.host/", x.send(:root_url)) - assert_equal("/", x.send(:root_path)) - end + # Use %20 for space instead. + results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F" + assert results, "Recognition should have succeeded" + assert_equal ['hello world', 'how are you?'], results[:path] - def test_named_route_with_regexps - rs.draw do |map| - map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show', - :year => /\d+/, :month => /\d+/, :day => /\d+/ - map.connect ':controller/:action/:id' - end - x = setup_for_named_route - # assert_equal( - # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false}, - # x.send(:article_url, :title => 'hi') - # ) - assert_equal( - "http://test.host/page/2005/6/10/hi", - x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6) - ) - end + results = rs.recognize_path "/file" + assert results, "Recognition should have succeeded" + assert_equal [], results[:path] + end - def test_changing_controller - @rs.draw {|m| m.connect ':controller/:action/:id' } + def test_paths_slashes_unescaped_with_ordered_parameters + rs.add_named_route :path, '/file/*path', :controller => 'content' - assert_equal '/admin/stuff/show/10', rs.generate( - {:controller => 'stuff', :action => 'show', :id => 10}, - {:controller => 'admin/user', :action => 'index'} - ) + # No / to %2F in URI, only for query params. + x = setup_for_named_route + assert_equal("/file/hello/world", x.send(:path_path, 'hello/world')) + end + + def test_non_controllers_cannot_be_matched + rs.draw do |map| + map.connect ':controller/:action/:id' end + assert_raise(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") } + end - def test_paths_escaped + def test_paths_do_not_accept_defaults + assert_raise(ActionController::RoutingError) do rs.draw do |map| - map.path 'file/*path', :controller => 'content', :action => 'show_file' + map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default) map.connect ':controller/:action/:id' end - - # No + to space in URI escaping, only for query params. - results = rs.recognize_path "/file/hello+world/how+are+you%3F" - assert results, "Recognition should have succeeded" - assert_equal ['hello+world', 'how+are+you?'], results[:path] - - # Use %20 for space instead. - results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F" - assert results, "Recognition should have succeeded" - assert_equal ['hello world', 'how are you?'], results[:path] - - results = rs.recognize_path "/file" - assert results, "Recognition should have succeeded" - assert_equal [], results[:path] end - def test_paths_slashes_unescaped_with_ordered_parameters - rs.add_named_route :path, '/file/*path', :controller => 'content' - - # No / to %2F in URI, only for query params. - x = setup_for_named_route - assert_equal("/file/hello/world", x.send(:path_path, 'hello/world')) + rs.draw do |map| + map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => [] + map.connect ':controller/:action/:id' end + end - def test_non_controllers_cannot_be_matched - rs.draw do |map| - map.connect ':controller/:action/:id' - end - assert_raises(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") } + def test_should_list_options_diff_when_routing_requirements_dont_match + rs.draw do |map| + map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/} end + exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") } + assert_match /^post_url failed to generate/, exception.message + from_match = exception.message.match(/from \{[^\}]+\}/).to_s + assert_match /:bad_param=>"foo"/, from_match + assert_match /:action=>"show"/, from_match + assert_match /:controller=>"post"/, from_match - def test_paths_do_not_accept_defaults - assert_raises(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' - end - end + expected_match = exception.message.match(/expected: \{[^\}]+\}/).to_s + assert_no_match /:bad_param=>"foo"/, expected_match + assert_match /:action=>"show"/, expected_match + assert_match /:controller=>"post"/, expected_match - rs.draw do |map| - map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => [] - map.connect ':controller/:action/:id' - end + diff_match = exception.message.match(/diff: \{[^\}]+\}/).to_s + assert_match /:bad_param=>"foo"/, diff_match + assert_no_match /:action=>"show"/, diff_match + assert_no_match /:controller=>"post"/, diff_match + end + + # this specifies the case where your formerly would get a very confusing error message with an empty diff + def test_should_have_better_error_message_when_options_diff_is_empty + rs.draw do |map| + map.content '/content/:query', :controller => 'content', :action => 'show' end - def test_should_list_options_diff_when_routing_requirements_dont_match - rs.draw do |map| - map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/} - end - exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") } - assert_match /^post_url failed to generate/, exception.message - from_match = exception.message.match(/from \{[^\}]+\}/).to_s - assert_match /:bad_param=>"foo"/, from_match - assert_match /:action=>"show"/, from_match - assert_match /:controller=>"post"/, from_match - - expected_match = exception.message.match(/expected: \{[^\}]+\}/).to_s - assert_no_match /:bad_param=>"foo"/, expected_match - assert_match /:action=>"show"/, expected_match - assert_match /:controller=>"post"/, expected_match - - diff_match = exception.message.match(/diff: \{[^\}]+\}/).to_s - assert_match /:bad_param=>"foo"/, diff_match - assert_no_match /:action=>"show"/, diff_match - assert_no_match /:controller=>"post"/, diff_match - end - - # this specifies the case where your formerly would get a very confusing error message with an empty diff - def test_should_have_better_error_message_when_options_diff_is_empty - rs.draw do |map| - map.content '/content/:query', :controller => 'content', :action => 'show' - end + exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'content', :action => 'show', :use_route => "content") } + assert_match %r[:action=>"show"], exception.message + assert_match %r[:controller=>"content"], exception.message + assert_match %r[you may have ambiguous routes, or you may need to supply additional parameters for this route], exception.message + assert_match %r[content_url has the following required parameters: \["content", :query\] - are they all satisfied?], exception.message + end - exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'content', :action => 'show', :use_route => "content") } - assert_match %r[:action=>"show"], exception.message - assert_match %r[:controller=>"content"], exception.message - assert_match %r[you may have ambiguous routes, or you may need to supply additional parameters for this route], exception.message - assert_match %r[content_url has the following required parameters: \["content", :query\] - are they all satisfied?], exception.message + def test_dynamic_path_allowed + rs.draw do |map| + map.connect '*path', :controller => 'content', :action => 'show_file' end - def test_dynamic_path_allowed - rs.draw do |map| - map.connect '*path', :controller => 'content', :action => 'show_file' - end + assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo)) + end - assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo)) + def test_dynamic_recall_paths_allowed + rs.draw do |map| + map.connect '*path', :controller => 'content', :action => 'show_file' end - def test_dynamic_recall_paths_allowed - rs.draw do |map| - map.connect '*path', :controller => 'content', :action => 'show_file' - end + recall_path = ActionController::Routing::PathSegment::Result.new(%w(pages boo)) + assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path) + end - recall_path = ActionController::Routing::PathSegment::Result.new(%w(pages boo)) - assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path) + def test_backwards + rs.draw do |map| + map.connect 'page/:id/:action', :controller => 'pages', :action => 'show' + map.connect ':controller/:action/:id' end - def test_backwards - rs.draw do |map| - map.connect 'page/:id/:action', :controller => 'pages', :action => 'show' - map.connect ':controller/:action/:id' - end + assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'}) + assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show') + assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo') + end - assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'}) - assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show') - assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo') + def test_route_with_fixnum_default + rs.draw do |map| + map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1 + map.connect ':controller/:action/:id' end - def test_route_with_fixnum_default - rs.draw do |map| - map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1 - map.connect ':controller/:action/:id' - end + assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page') + assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1) + assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1') + assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10) - assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page') - assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1) - assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1') - assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10) + assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page")) + assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1")) + assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10")) + end - assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page")) - assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1")) - assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10")) + # For newer revision + def test_route_with_text_default + rs.draw do |map| + map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1 + map.connect ':controller/:action/:id' end - # For newer revision - def test_route_with_text_default - rs.draw do |map| - map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1 - map.connect ':controller/:action/:id' - end + assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo') + assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo")) - assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo') - assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo")) + token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian + token.force_encoding("UTF-8") if token.respond_to?(:force_encoding) + escaped_token = CGI::escape(token) - token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian - escaped_token = CGI::escape(token) + assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token) + assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_token}")) + end - assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token) - assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_token}")) - end + def test_action_expiry + @rs.draw {|m| m.connect ':controller/:action/:id' } + assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'}) + end - def test_action_expiry - @rs.draw {|m| m.connect ':controller/:action/:id' } - assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'}) - end + def test_recognition_with_uppercase_controller_name + @rs.draw {|m| m.connect ':controller/:action/:id' } + assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content")) + assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list")) + assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10")) - def test_recognition_with_uppercase_controller_name - @rs.draw {|m| m.connect ':controller/:action/:id' } - assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content")) - assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list")) - assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10")) + # these used to work, before the routes rewrite, but support for this was pulled in the new version... + #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/NewsFeed")) + #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/News_Feed")) + end - # these used to work, before the routes rewrite, but support for this was pulled in the new version... - #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/NewsFeed")) - #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/News_Feed")) + def test_requirement_should_prevent_optional_id + rs.draw do |map| + map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/} end - def test_requirement_should_prevent_optional_id - rs.draw do |map| - map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/} - end + assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10) - assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10) + assert_raise ActionController::RoutingError do + rs.generate(:controller => 'post', :action => 'show') + end + end - assert_raises ActionController::RoutingError do - rs.generate(:controller => 'post', :action => 'show') - end + def test_both_requirement_and_optional + rs.draw do |map| + map.blog('test/:year', :controller => 'post', :action => 'show', + :defaults => { :year => nil }, + :requirements => { :year => /\d{4}/ } + ) + map.connect ':controller/:action/:id' end - def test_both_requirement_and_optional - rs.draw do |map| - map.blog('test/:year', :controller => 'post', :action => 'show', - :defaults => { :year => nil }, - :requirements => { :year => /\d{4}/ } - ) - map.connect ':controller/:action/:id' - end + assert_equal '/test', rs.generate(:controller => 'post', :action => 'show') + assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil) - assert_equal '/test', rs.generate(:controller => 'post', :action => 'show') - assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil) + x = setup_for_named_route + assert_equal("http://test.host/test", + x.send(:blog_url)) + end - x = setup_for_named_route - assert_equal("http://test.host/test", - x.send(:blog_url)) + def test_set_to_nil_forgets + rs.draw do |map| + map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil + map.connect ':controller/:action/:id' end - def test_set_to_nil_forgets - rs.draw do |map| - map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil - map.connect ':controller/:action/:id' - end + assert_equal '/pages/2005', + rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005) + assert_equal '/pages/2005/6', + rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6) + assert_equal '/pages/2005/6/12', + rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12) - assert_equal '/pages/2005', - rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005) - assert_equal '/pages/2005/6', - rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6) - assert_equal '/pages/2005/6/12', - rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12) + assert_equal '/pages/2005/6/4', + rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) - assert_equal '/pages/2005/6/4', - rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) + assert_equal '/pages/2005/6', + rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) - assert_equal '/pages/2005/6', - rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) + assert_equal '/pages/2005', + rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) + end - assert_equal '/pages/2005', - rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) + def test_url_with_no_action_specified + rs.draw do |map| + map.connect '', :controller => 'content' + map.connect ':controller/:action/:id' end - def test_url_with_no_action_specified - rs.draw do |map| - map.connect '', :controller => 'content' - map.connect ':controller/:action/:id' - end + assert_equal '/', rs.generate(:controller => 'content', :action => 'index') + assert_equal '/', rs.generate(:controller => 'content') + end - assert_equal '/', rs.generate(:controller => 'content', :action => 'index') - assert_equal '/', rs.generate(:controller => 'content') + def test_named_url_with_no_action_specified + rs.draw do |map| + map.home '', :controller => 'content' + map.connect ':controller/:action/:id' end - def test_named_url_with_no_action_specified + assert_equal '/', rs.generate(:controller => 'content', :action => 'index') + assert_equal '/', rs.generate(:controller => 'content') + + x = setup_for_named_route + assert_equal("http://test.host/", + x.send(:home_url)) + end + + def test_url_generated_when_forgetting_action + [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash| rs.draw do |map| - map.home '', :controller => 'content' + map.home '', hash map.connect ':controller/:action/:id' end - - assert_equal '/', rs.generate(:controller => 'content', :action => 'index') - assert_equal '/', rs.generate(:controller => 'content') - - x = setup_for_named_route - assert_equal("http://test.host/", - x.send(:home_url)) + assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'}) + assert_equal '/', rs.generate({:controller => 'content'}) + assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'}) end + end - def test_url_generated_when_forgetting_action - [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash| - rs.draw do |map| - map.home '', hash - map.connect ':controller/:action/:id' - end - assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'}) - assert_equal '/', rs.generate({:controller => 'content'}) - assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'}) - end + def test_named_route_method + rs.draw do |map| + map.categories 'categories', :controller => 'content', :action => 'categories' + map.connect ':controller/:action/:id' end - def test_named_route_method - rs.draw do |map| - map.categories 'categories', :controller => 'content', :action => 'categories' - map.connect ':controller/:action/:id' - end + assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories') + assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'}) + end - assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories') - assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'}) - end + def test_named_routes_array + test_named_route_method + assert_equal [:categories], rs.named_routes.names + end - def test_named_routes_array - test_named_route_method - assert_equal [:categories], rs.named_routes.names + def test_nil_defaults + rs.draw do |map| + map.connect 'journal', + :controller => 'content', + :action => 'list_journal', + :date => nil, :user_id => nil + map.connect ':controller/:action/:id' end - def test_nil_defaults - rs.draw do |map| - map.connect 'journal', - :controller => 'content', - :action => 'list_journal', - :date => nil, :user_id => nil - map.connect ':controller/:action/:id' - end + assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil) + end + + def setup_request_method_routes_for(method) + @request = ActionController::TestRequest.new + @request.env["REQUEST_METHOD"] = method + @request.request_uri = "/match" - assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil) + rs.draw do |r| + r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get } + r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post } + r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put } + r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete } end + end + + %w(GET POST PUT DELETE).each do |request_method| + define_method("test_request_method_recognized_with_#{request_method}") do + begin + Object.const_set(:BooksController, Class.new(ActionController::Base)) - def setup_request_method_routes_for(method) - @request = ActionController::TestRequest.new - @request.env["REQUEST_METHOD"] = method - @request.request_uri = "/match" + setup_request_method_routes_for(request_method) - rs.draw do |r| - r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get } - r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post } - r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put } - r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete } + assert_nothing_raised { rs.recognize(@request) } + assert_equal request_method.downcase, @request.path_parameters[:action] + ensure + Object.send(:remove_const, :BooksController) rescue nil end end + end - %w(GET POST PUT DELETE).each do |request_method| - define_method("test_request_method_recognized_with_#{request_method}") do - begin - Object.const_set(:BooksController, Class.new(ActionController::Base)) + def test_recognize_array_of_methods + Object.const_set(:BooksController, Class.new(ActionController::Base)) + rs.draw do |r| + r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] } + r.connect '/match', :controller => 'books', :action => 'not_get_or_post' + end - setup_request_method_routes_for(request_method) + @request = ActionController::TestRequest.new + @request.env["REQUEST_METHOD"] = 'POST' + @request.request_uri = "/match" + assert_nothing_raised { rs.recognize(@request) } + assert_equal 'get_or_post', @request.path_parameters[:action] - assert_nothing_raised { rs.recognize(@request) } - assert_equal request_method.downcase, @request.path_parameters[:action] - ensure - Object.send(:remove_const, :BooksController) rescue nil - end - end + # have to recreate or else the RouteSet uses a cached version: + @request = ActionController::TestRequest.new + @request.env["REQUEST_METHOD"] = 'PUT' + @request.request_uri = "/match" + assert_nothing_raised { rs.recognize(@request) } + assert_equal 'not_get_or_post', @request.path_parameters[:action] + ensure + Object.send(:remove_const, :BooksController) rescue nil + end + + def test_subpath_recognized + Object.const_set(:SubpathBooksController, Class.new(ActionController::Base)) + + rs.draw do |r| + r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit' + r.connect '/items/:id/:action', :controller => 'subpath_books' + r.connect '/posts/new/:action', :controller => 'subpath_books' + r.connect '/posts/:id', :controller => 'subpath_books', :action => "show" end - def test_recognize_array_of_methods - Object.const_set(:BooksController, Class.new(ActionController::Base)) - rs.draw do |r| - r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] } - r.connect '/match', :controller => 'books', :action => 'not_get_or_post' - end + hash = rs.recognize_path "/books/17/edit" + assert_not_nil hash + assert_equal %w(subpath_books 17 edit), [hash[:controller], hash[:id], hash[:action]] - @request = ActionController::TestRequest.new - @request.env["REQUEST_METHOD"] = 'POST' - @request.request_uri = "/match" - assert_nothing_raised { rs.recognize(@request) } - assert_equal 'get_or_post', @request.path_parameters[:action] - - # have to recreate or else the RouteSet uses a cached version: - @request = ActionController::TestRequest.new - @request.env["REQUEST_METHOD"] = 'PUT' - @request.request_uri = "/match" - assert_nothing_raised { rs.recognize(@request) } - assert_equal 'not_get_or_post', @request.path_parameters[:action] - ensure - Object.send(:remove_const, :BooksController) rescue nil - end - - def test_subpath_recognized - Object.const_set(:SubpathBooksController, Class.new(ActionController::Base)) - - rs.draw do |r| - r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit' - r.connect '/items/:id/:action', :controller => 'subpath_books' - r.connect '/posts/new/:action', :controller => 'subpath_books' - r.connect '/posts/:id', :controller => 'subpath_books', :action => "show" - end + hash = rs.recognize_path "/items/3/complete" + assert_not_nil hash + assert_equal %w(subpath_books 3 complete), [hash[:controller], hash[:id], hash[:action]] - hash = rs.recognize_path "/books/17/edit" - assert_not_nil hash - assert_equal %w(subpath_books 17 edit), [hash[:controller], hash[:id], hash[:action]] + hash = rs.recognize_path "/posts/new/preview" + assert_not_nil hash + assert_equal %w(subpath_books preview), [hash[:controller], hash[:action]] - hash = rs.recognize_path "/items/3/complete" - assert_not_nil hash - assert_equal %w(subpath_books 3 complete), [hash[:controller], hash[:id], hash[:action]] + hash = rs.recognize_path "/posts/7" + assert_not_nil hash + assert_equal %w(subpath_books show 7), [hash[:controller], hash[:action], hash[:id]] + ensure + Object.send(:remove_const, :SubpathBooksController) rescue nil + end - hash = rs.recognize_path "/posts/new/preview" - assert_not_nil hash - assert_equal %w(subpath_books preview), [hash[:controller], hash[:action]] + def test_subpath_generated + Object.const_set(:SubpathBooksController, Class.new(ActionController::Base)) - hash = rs.recognize_path "/posts/7" - assert_not_nil hash - assert_equal %w(subpath_books show 7), [hash[:controller], hash[:action], hash[:id]] - ensure - Object.send(:remove_const, :SubpathBooksController) rescue nil + rs.draw do |r| + r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit' + r.connect '/items/:id/:action', :controller => 'subpath_books' + r.connect '/posts/new/:action', :controller => 'subpath_books' end - def test_subpath_generated - Object.const_set(:SubpathBooksController, Class.new(ActionController::Base)) - - rs.draw do |r| - r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit' - r.connect '/items/:id/:action', :controller => 'subpath_books' - r.connect '/posts/new/:action', :controller => 'subpath_books' - end + assert_equal "/books/7/edit", rs.generate(:controller => "subpath_books", :id => 7, :action => "edit") + assert_equal "/items/15/complete", rs.generate(:controller => "subpath_books", :id => 15, :action => "complete") + assert_equal "/posts/new/preview", rs.generate(:controller => "subpath_books", :action => "preview") + ensure + Object.send(:remove_const, :SubpathBooksController) rescue nil + end - assert_equal "/books/7/edit", rs.generate(:controller => "subpath_books", :id => 7, :action => "edit") - assert_equal "/items/15/complete", rs.generate(:controller => "subpath_books", :id => 15, :action => "complete") - assert_equal "/posts/new/preview", rs.generate(:controller => "subpath_books", :action => "preview") - ensure - Object.send(:remove_const, :SubpathBooksController) rescue nil + def test_failed_requirements_raises_exception_with_violated_requirements + rs.draw do |r| + r.foo_with_requirement 'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+/} end - def test_failed_requirements_raises_exception_with_violated_requirements - rs.draw do |r| - r.foo_with_requirement 'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+/} - end + x = setup_for_named_route + assert_raise(ActionController::RoutingError) do + x.send(:foo_with_requirement_url, "I am Against the requirements") + end + end - x = setup_for_named_route - assert_raises(ActionController::RoutingError) do - x.send(:foo_with_requirement_url, "I am Against the requirements") - end + def test_routes_changed_correctly_after_clear + ActionController::Base.optimise_named_routes = true + rs = ::ActionController::Routing::RouteSet.new + rs.draw do |r| + r.connect 'ca', :controller => 'ca', :action => "aa" + r.connect 'cb', :controller => 'cb', :action => "ab" + r.connect 'cc', :controller => 'cc', :action => "ac" + r.connect ':controller/:action/:id' + r.connect ':controller/:action/:id.:format' end - def test_routes_changed_correctly_after_clear - ActionController::Base.optimise_named_routes = true - rs = ::ActionController::Routing::RouteSet.new - rs.draw do |r| - r.connect 'ca', :controller => 'ca', :action => "aa" - r.connect 'cb', :controller => 'cb', :action => "ab" - r.connect 'cc', :controller => 'cc', :action => "ac" - r.connect ':controller/:action/:id' - r.connect ':controller/:action/:id.:format' - end + hash = rs.recognize_path "/cc" - hash = rs.recognize_path "/cc" + assert_not_nil hash + assert_equal %w(cc ac), [hash[:controller], hash[:action]] - assert_not_nil hash - assert_equal %w(cc ac), [hash[:controller], hash[:action]] + rs.draw do |r| + r.connect 'cb', :controller => 'cb', :action => "ab" + r.connect 'cc', :controller => 'cc', :action => "ac" + r.connect ':controller/:action/:id' + r.connect ':controller/:action/:id.:format' + end - rs.draw do |r| - r.connect 'cb', :controller => 'cb', :action => "ab" - r.connect 'cc', :controller => 'cc', :action => "ac" - r.connect ':controller/:action/:id' - r.connect ':controller/:action/:id.:format' - end + hash = rs.recognize_path "/cc" - hash = rs.recognize_path "/cc" + assert_not_nil hash + assert_equal %w(cc ac), [hash[:controller], hash[:action]] - assert_not_nil hash - assert_equal %w(cc ac), [hash[:controller], hash[:action]] + end +end - end +class RouteTest < Test::Unit::TestCase + def setup + @route = ROUTING::Route.new end - class RouteTest < Test::Unit::TestCase - def setup - @route = ROUTING::Route.new - end + def slash_segment(is_optional = false) + ROUTING::DividerSegment.new('/', :optional => is_optional) + end - def slash_segment(is_optional = false) - ROUTING::DividerSegment.new('/', :optional => is_optional) + def default_route + unless defined?(@default_route) + segments = [] + segments << ROUTING::StaticSegment.new('/', :raw => true) + segments << ROUTING::DynamicSegment.new(:controller) + segments << slash_segment(:optional) + segments << ROUTING::DynamicSegment.new(:action, :default => 'index', :optional => true) + segments << slash_segment(:optional) + segments << ROUTING::DynamicSegment.new(:id, :optional => true) + segments << slash_segment(:optional) + @default_route = ROUTING::Route.new(segments).freeze end + @default_route + end - def default_route - unless defined?(@default_route) - segments = [] - segments << ROUTING::StaticSegment.new('/', :raw => true) - segments << ROUTING::DynamicSegment.new(:controller) - segments << slash_segment(:optional) - segments << ROUTING::DynamicSegment.new(:action, :default => 'index', :optional => true) - segments << slash_segment(:optional) - segments << ROUTING::DynamicSegment.new(:id, :optional => true) - segments << slash_segment(:optional) - @default_route = ROUTING::Route.new(segments).freeze - end - @default_route - end + def test_default_route_recognition + expected = {:controller => 'accounts', :action => 'show', :id => '10'} + assert_equal expected, default_route.recognize('/accounts/show/10') + assert_equal expected, default_route.recognize('/accounts/show/10/') - def test_default_route_recognition - expected = {:controller => 'accounts', :action => 'show', :id => '10'} - assert_equal expected, default_route.recognize('/accounts/show/10') - assert_equal expected, default_route.recognize('/accounts/show/10/') + expected[:id] = 'jamis' + assert_equal expected, default_route.recognize('/accounts/show/jamis/') - expected[:id] = 'jamis' - assert_equal expected, default_route.recognize('/accounts/show/jamis/') + expected.delete :id + assert_equal expected, default_route.recognize('/accounts/show') + assert_equal expected, default_route.recognize('/accounts/show/') - expected.delete :id - assert_equal expected, default_route.recognize('/accounts/show') - assert_equal expected, default_route.recognize('/accounts/show/') + expected[:action] = 'index' + assert_equal expected, default_route.recognize('/accounts/') + assert_equal expected, default_route.recognize('/accounts') - expected[:action] = 'index' - assert_equal expected, default_route.recognize('/accounts/') - assert_equal expected, default_route.recognize('/accounts') + assert_equal nil, default_route.recognize('/') + assert_equal nil, default_route.recognize('/accounts/how/goood/it/is/to/be/free') + end - assert_equal nil, default_route.recognize('/') - assert_equal nil, default_route.recognize('/accounts/how/goood/it/is/to/be/free') - end + def test_default_route_should_omit_default_action + o = {:controller => 'accounts', :action => 'index'} + assert_equal '/accounts', default_route.generate(o, o, {}) + end - def test_default_route_should_omit_default_action - o = {:controller => 'accounts', :action => 'index'} - assert_equal '/accounts', default_route.generate(o, o, {}) - end + def test_default_route_should_include_default_action_when_id_present + o = {:controller => 'accounts', :action => 'index', :id => '20'} + assert_equal '/accounts/index/20', default_route.generate(o, o, {}) + end - def test_default_route_should_include_default_action_when_id_present - o = {:controller => 'accounts', :action => 'index', :id => '20'} - assert_equal '/accounts/index/20', default_route.generate(o, o, {}) - end + def test_default_route_should_work_with_action_but_no_id + o = {:controller => 'accounts', :action => 'list_all'} + assert_equal '/accounts/list_all', default_route.generate(o, o, {}) + end - def test_default_route_should_work_with_action_but_no_id - o = {:controller => 'accounts', :action => 'list_all'} - assert_equal '/accounts/list_all', default_route.generate(o, o, {}) - end + def test_default_route_should_uri_escape_pluses + expected = { :controller => 'accounts', :action => 'show', :id => 'hello world' } + assert_equal expected, default_route.recognize('/accounts/show/hello world') + assert_equal expected, default_route.recognize('/accounts/show/hello%20world') + assert_equal '/accounts/show/hello%20world', default_route.generate(expected, expected, {}) - def test_default_route_should_uri_escape_pluses - expected = { :controller => 'accounts', :action => 'show', :id => 'hello world' } - assert_equal expected, default_route.recognize('/accounts/show/hello world') - assert_equal expected, default_route.recognize('/accounts/show/hello%20world') - assert_equal '/accounts/show/hello%20world', default_route.generate(expected, expected, {}) + expected[:id] = 'hello+world' + assert_equal expected, default_route.recognize('/accounts/show/hello+world') + assert_equal expected, default_route.recognize('/accounts/show/hello%2Bworld') + assert_equal '/accounts/show/hello+world', default_route.generate(expected, expected, {}) + end - expected[:id] = 'hello+world' - assert_equal expected, default_route.recognize('/accounts/show/hello+world') - assert_equal expected, default_route.recognize('/accounts/show/hello%2Bworld') - assert_equal '/accounts/show/hello+world', default_route.generate(expected, expected, {}) - end + def test_matches_controller_and_action + # requirement_for should only be called for the action and controller _once_ + @route.expects(:requirement_for).with(:controller).times(1).returns('pages') + @route.expects(:requirement_for).with(:action).times(1).returns('show') - def test_matches_controller_and_action - # requirement_for should only be called for the action and controller _once_ - @route.expects(:requirement_for).with(:controller).times(1).returns('pages') - @route.expects(:requirement_for).with(:action).times(1).returns('show') + @route.requirements = {:controller => 'pages', :action => 'show'} + assert @route.matches_controller_and_action?('pages', 'show') + assert !@route.matches_controller_and_action?('not_pages', 'show') + assert !@route.matches_controller_and_action?('pages', 'not_show') + end - @route.requirements = {:controller => 'pages', :action => 'show'} - assert @route.matches_controller_and_action?('pages', 'show') - assert !@route.matches_controller_and_action?('not_pages', 'show') - assert !@route.matches_controller_and_action?('pages', 'not_show') - end + def test_parameter_shell + page_url = ROUTING::Route.new + page_url.requirements = {:controller => 'pages', :action => 'show', :id => /\d+/} + assert_equal({:controller => 'pages', :action => 'show'}, page_url.parameter_shell) + end - def test_parameter_shell - page_url = ROUTING::Route.new - page_url.requirements = {:controller => 'pages', :action => 'show', :id => /\d+/} - assert_equal({:controller => 'pages', :action => 'show'}, page_url.parameter_shell) - end + def test_defaults + route = ROUTING::RouteBuilder.new.build '/users/:id.:format', :controller => "users", :action => "show", :format => "html" + assert_equal( + { :controller => "users", :action => "show", :format => "html" }, + route.defaults) + end - def test_defaults - route = ROUTING::RouteBuilder.new.build '/users/:id.:format', :controller => "users", :action => "show", :format => "html" - assert_equal( - { :controller => "users", :action => "show", :format => "html" }, - route.defaults) + def test_builder_complains_without_controller + assert_raise(ArgumentError) do + ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index" end + end - def test_builder_complains_without_controller - assert_raises(ArgumentError) do - ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index" - end - end + def test_significant_keys_for_default_route + keys = default_route.significant_keys.sort_by {|k| k.to_s } + assert_equal [:action, :controller, :id], keys + end - def test_significant_keys_for_default_route - keys = default_route.significant_keys.sort_by {|k| k.to_s } - assert_equal [:action, :controller, :id], keys - end + def test_significant_keys + segments = [] + segments << ROUTING::StaticSegment.new('/', :raw => true) + segments << ROUTING::StaticSegment.new('user') + segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true) + segments << ROUTING::DynamicSegment.new(:user) + segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true) - def test_significant_keys - segments = [] - segments << ROUTING::StaticSegment.new('/', :raw => true) - segments << ROUTING::StaticSegment.new('user') - segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true) - segments << ROUTING::DynamicSegment.new(:user) - segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true) + requirements = {:controller => 'users', :action => 'show'} - requirements = {:controller => 'users', :action => 'show'} + user_url = ROUTING::Route.new(segments, requirements) + keys = user_url.significant_keys.sort_by { |k| k.to_s } + assert_equal [:action, :controller, :user], keys + end - user_url = ROUTING::Route.new(segments, requirements) - keys = user_url.significant_keys.sort_by { |k| k.to_s } - assert_equal [:action, :controller, :user], keys - end + def test_build_empty_query_string + assert_equal '', @route.build_query_string({}) + end - def test_build_empty_query_string - assert_equal '', @route.build_query_string({}) - end + def test_build_query_string_with_nil_value + assert_equal '', @route.build_query_string({:x => nil}) + end - def test_build_query_string_with_nil_value - assert_equal '', @route.build_query_string({:x => nil}) - end + def test_simple_build_query_string + assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => '1', :y => '2')) + end - def test_simple_build_query_string - assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => '1', :y => '2')) - end + def test_convert_ints_build_query_string + assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => 1, :y => 2)) + end - def test_convert_ints_build_query_string - assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => 1, :y => 2)) - end + def test_escape_spaces_build_query_string + assert_equal '?x=hello+world&y=goodbye+world', order_query_string(@route.build_query_string(:x => 'hello world', :y => 'goodbye world')) + end - def test_escape_spaces_build_query_string - assert_equal '?x=hello+world&y=goodbye+world', order_query_string(@route.build_query_string(:x => 'hello world', :y => 'goodbye world')) - end + def test_expand_array_build_query_string + assert_equal '?x%5B%5D=1&x%5B%5D=2', order_query_string(@route.build_query_string(:x => [1, 2])) + end - def test_expand_array_build_query_string - assert_equal '?x%5B%5D=1&x%5B%5D=2', order_query_string(@route.build_query_string(:x => [1, 2])) - end + def test_escape_spaces_build_query_string_selected_keys + assert_equal '?x=hello+world', order_query_string(@route.build_query_string({:x => 'hello world', :y => 'goodbye world'}, [:x])) + end - def test_escape_spaces_build_query_string_selected_keys - assert_equal '?x=hello+world', order_query_string(@route.build_query_string({:x => 'hello world', :y => 'goodbye world'}, [:x])) + private + def order_query_string(qs) + '?' + qs[1..-1].split('&').sort.join('&') end +end - private - def order_query_string(qs) - '?' + qs[1..-1].split('&').sort.join('&') - end +class RouteSetTest < Test::Unit::TestCase + def set + @set ||= ROUTING::RouteSet.new end - class RouteSetTest < Test::Unit::TestCase - def set - @set ||= ROUTING::RouteSet.new - end + def request + @request ||= ActionController::TestRequest.new + end - def request - @request ||= ActionController::TestRequest.new - end + def test_generate_extras + set.draw { |m| m.connect ':controller/:action/:id' } + path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") + assert_equal "/foo/bar/15", path + assert_equal %w(that this), extras.map(&:to_s).sort + end - def test_generate_extras - set.draw { |m| m.connect ':controller/:action/:id' } - path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") - assert_equal "/foo/bar/15", path - assert_equal %w(that this), extras.map(&:to_s).sort - end + def test_extra_keys + set.draw { |m| m.connect ':controller/:action/:id' } + extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") + assert_equal %w(that this), extras.map(&:to_s).sort + end - def test_extra_keys - set.draw { |m| m.connect ':controller/:action/:id' } - extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") - assert_equal %w(that this), extras.map(&:to_s).sort + def test_generate_extras_not_first + set.draw do |map| + map.connect ':controller/:action/:id.:format' + map.connect ':controller/:action/:id' end + path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") + assert_equal "/foo/bar/15", path + assert_equal %w(that this), extras.map(&:to_s).sort + end - def test_generate_extras_not_first - set.draw do |map| - map.connect ':controller/:action/:id.:format' - map.connect ':controller/:action/:id' - end - path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") - assert_equal "/foo/bar/15", path - assert_equal %w(that this), extras.map(&:to_s).sort + def test_generate_not_first + set.draw do |map| + map.connect ':controller/:action/:id.:format' + map.connect ':controller/:action/:id' end + assert_equal "/foo/bar/15?this=hello", set.generate(:controller => "foo", :action => "bar", :id => 15, :this => "hello") + end - def test_generate_not_first - set.draw do |map| - map.connect ':controller/:action/:id.:format' - map.connect ':controller/:action/:id' - end - assert_equal "/foo/bar/15?this=hello", set.generate(:controller => "foo", :action => "bar", :id => 15, :this => "hello") + def test_extra_keys_not_first + set.draw do |map| + map.connect ':controller/:action/:id.:format' + map.connect ':controller/:action/:id' end + extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") + assert_equal %w(that this), extras.map(&:to_s).sort + end - def test_extra_keys_not_first - set.draw do |map| - map.connect ':controller/:action/:id.:format' - map.connect ':controller/:action/:id' - end - extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") - assert_equal %w(that this), extras.map(&:to_s).sort + def test_draw + assert_equal 0, set.routes.size + set.draw do |map| + map.connect '/hello/world', :controller => 'a', :action => 'b' end + assert_equal 1, set.routes.size + end - def test_draw - assert_equal 0, set.routes.size - set.draw do |map| - map.connect '/hello/world', :controller => 'a', :action => 'b' - end - assert_equal 1, set.routes.size + def test_named_draw + assert_equal 0, set.routes.size + set.draw do |map| + map.hello '/hello/world', :controller => 'a', :action => 'b' end + assert_equal 1, set.routes.size + assert_equal set.routes.first, set.named_routes[:hello] + end - def test_named_draw - assert_equal 0, set.routes.size - set.draw do |map| - map.hello '/hello/world', :controller => 'a', :action => 'b' - end - assert_equal 1, set.routes.size - assert_equal set.routes.first, set.named_routes[:hello] + def test_later_named_routes_take_precedence + set.draw do |map| + map.hello '/hello/world', :controller => 'a', :action => 'b' + map.hello '/hello', :controller => 'a', :action => 'b' end + assert_equal set.routes.last, set.named_routes[:hello] + end - def test_later_named_routes_take_precedence - set.draw do |map| - map.hello '/hello/world', :controller => 'a', :action => 'b' - map.hello '/hello', :controller => 'a', :action => 'b' - end - assert_equal set.routes.last, set.named_routes[:hello] + def setup_named_route_test + set.draw do |map| + map.show '/people/:id', :controller => 'people', :action => 'show' + map.index '/people', :controller => 'people', :action => 'index' + map.multi '/people/go/:foo/:bar/joe/:id', :controller => 'people', :action => 'multi' + map.users '/admin/users', :controller => 'admin/users', :action => 'index' end - def setup_named_route_test - set.draw do |map| - map.show '/people/:id', :controller => 'people', :action => 'show' - map.index '/people', :controller => 'people', :action => 'index' - map.multi '/people/go/:foo/:bar/joe/:id', :controller => 'people', :action => 'multi' - map.users '/admin/users', :controller => 'admin/users', :action => 'index' - end + klass = Class.new(MockController) + set.install_helpers(klass) + klass.new(set) + end - klass = Class.new(MockController) - set.install_helpers(klass) - klass.new(set) - end + def test_named_route_hash_access_method + controller = setup_named_route_test - def test_named_route_hash_access_method - controller = setup_named_route_test + assert_equal( + { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => false }, + controller.send(:hash_for_show_url, :id => 5)) - assert_equal( - { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => false }, - controller.send(:hash_for_show_url, :id => 5)) + assert_equal( + { :controller => 'people', :action => 'index', :use_route => :index, :only_path => false }, + controller.send(:hash_for_index_url)) - assert_equal( - { :controller => 'people', :action => 'index', :use_route => :index, :only_path => false }, - controller.send(:hash_for_index_url)) + assert_equal( + { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => true }, + controller.send(:hash_for_show_path, :id => 5) + ) + end - assert_equal( - { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => true }, - controller.send(:hash_for_show_path, :id => 5) - ) - end + def test_named_route_url_method + controller = setup_named_route_test - def test_named_route_url_method - controller = setup_named_route_test + assert_equal "http://test.host/people/5", controller.send(:show_url, :id => 5) + assert_equal "/people/5", controller.send(:show_path, :id => 5) - assert_equal "http://test.host/people/5", controller.send(:show_url, :id => 5) - assert_equal "/people/5", controller.send(:show_path, :id => 5) + assert_equal "http://test.host/people", controller.send(:index_url) + assert_equal "/people", controller.send(:index_path) - assert_equal "http://test.host/people", controller.send(:index_url) - assert_equal "/people", controller.send(:index_path) + assert_equal "http://test.host/admin/users", controller.send(:users_url) + assert_equal '/admin/users', controller.send(:users_path) + assert_equal '/admin/users', set.generate(controller.send(:hash_for_users_url), {:controller => 'users', :action => 'index'}) + end - assert_equal "http://test.host/admin/users", controller.send(:users_url) - assert_equal '/admin/users', controller.send(:users_path) - assert_equal '/admin/users', set.generate(controller.send(:hash_for_users_url), {:controller => 'users', :action => 'index'}) - end + def test_named_route_url_method_with_anchor + controller = setup_named_route_test - def test_named_route_url_method_with_anchor - controller = setup_named_route_test + assert_equal "http://test.host/people/5#location", controller.send(:show_url, :id => 5, :anchor => 'location') + assert_equal "/people/5#location", controller.send(:show_path, :id => 5, :anchor => 'location') - assert_equal "http://test.host/people/5#location", controller.send(:show_url, :id => 5, :anchor => 'location') - assert_equal "/people/5#location", controller.send(:show_path, :id => 5, :anchor => 'location') + assert_equal "http://test.host/people#location", controller.send(:index_url, :anchor => 'location') + assert_equal "/people#location", controller.send(:index_path, :anchor => 'location') - assert_equal "http://test.host/people#location", controller.send(:index_url, :anchor => 'location') - assert_equal "/people#location", controller.send(:index_path, :anchor => 'location') + assert_equal "http://test.host/admin/users#location", controller.send(:users_url, :anchor => 'location') + assert_equal '/admin/users#location', controller.send(:users_path, :anchor => 'location') - assert_equal "http://test.host/admin/users#location", controller.send(:users_url, :anchor => 'location') - assert_equal '/admin/users#location', controller.send(:users_path, :anchor => 'location') + assert_equal "http://test.host/people/go/7/hello/joe/5#location", + controller.send(:multi_url, 7, "hello", 5, :anchor => 'location') - assert_equal "http://test.host/people/go/7/hello/joe/5#location", - controller.send(:multi_url, 7, "hello", 5, :anchor => 'location') + assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar#location", + controller.send(:multi_url, 7, "hello", 5, :baz => "bar", :anchor => 'location') - assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar#location", - controller.send(:multi_url, 7, "hello", 5, :baz => "bar", :anchor => 'location') + assert_equal "http://test.host/people?baz=bar#location", + controller.send(:index_url, :baz => "bar", :anchor => 'location') + end - assert_equal "http://test.host/people?baz=bar#location", - controller.send(:index_url, :baz => "bar", :anchor => 'location') - end + def test_named_route_url_method_with_port + controller = setup_named_route_test + assert_equal "http://test.host:8080/people/5", controller.send(:show_url, 5, :port=>8080) + end - def test_named_route_url_method_with_port - controller = setup_named_route_test - assert_equal "http://test.host:8080/people/5", controller.send(:show_url, 5, :port=>8080) - end + def test_named_route_url_method_with_host + controller = setup_named_route_test + assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com") + end - def test_named_route_url_method_with_host - controller = setup_named_route_test - assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com") - end + def test_named_route_url_method_with_protocol + controller = setup_named_route_test + assert_equal "https://test.host/people/5", controller.send(:show_url, 5, :protocol => "https") + end - def test_named_route_url_method_with_protocol - controller = setup_named_route_test - assert_equal "https://test.host/people/5", controller.send(:show_url, 5, :protocol => "https") - end + def test_named_route_url_method_with_ordered_parameters + controller = setup_named_route_test + assert_equal "http://test.host/people/go/7/hello/joe/5", + controller.send(:multi_url, 7, "hello", 5) + end - def test_named_route_url_method_with_ordered_parameters - controller = setup_named_route_test - assert_equal "http://test.host/people/go/7/hello/joe/5", - controller.send(:multi_url, 7, "hello", 5) - end + def test_named_route_url_method_with_ordered_parameters_and_hash + controller = setup_named_route_test + assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar", + controller.send(:multi_url, 7, "hello", 5, :baz => "bar") + end - def test_named_route_url_method_with_ordered_parameters_and_hash - controller = setup_named_route_test - assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar", - controller.send(:multi_url, 7, "hello", 5, :baz => "bar") - end + def test_named_route_url_method_with_ordered_parameters_and_empty_hash + controller = setup_named_route_test + assert_equal "http://test.host/people/go/7/hello/joe/5", + controller.send(:multi_url, 7, "hello", 5, {}) + end - def test_named_route_url_method_with_ordered_parameters_and_empty_hash - controller = setup_named_route_test - assert_equal "http://test.host/people/go/7/hello/joe/5", - controller.send(:multi_url, 7, "hello", 5, {}) - end + def test_named_route_url_method_with_no_positional_arguments + controller = setup_named_route_test + assert_equal "http://test.host/people?baz=bar", + controller.send(:index_url, :baz => "bar") + end - def test_named_route_url_method_with_no_positional_arguments - controller = setup_named_route_test - assert_equal "http://test.host/people?baz=bar", - controller.send(:index_url, :baz => "bar") - end + def test_draw_default_route + ActionController::Routing.with_controllers(['users']) do + set.draw do |map| + map.connect '/:controller/:action/:id' + end - def test_draw_default_route - ActionController::Routing.with_controllers(['users']) do - set.draw do |map| - map.connect '/:controller/:action/:id' - end + assert_equal 1, set.routes.size + route = set.routes.first - assert_equal 1, set.routes.size - route = set.routes.first + assert route.segments.last.optional? - assert route.segments.last.optional? + assert_equal '/users/show/10', set.generate(:controller => 'users', :action => 'show', :id => 10) + assert_equal '/users/index/10', set.generate(:controller => 'users', :id => 10) - assert_equal '/users/show/10', set.generate(:controller => 'users', :action => 'show', :id => 10) - assert_equal '/users/index/10', set.generate(:controller => 'users', :id => 10) + assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10')) + assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10/')) + end + end - assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10')) - assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10/')) + def test_draw_default_route_with_default_controller + ActionController::Routing.with_controllers(['users']) do + set.draw do |map| + map.connect '/:controller/:action/:id', :controller => 'users' end + assert_equal({:controller => 'users', :action => 'index'}, set.recognize_path('/')) end + end - def test_draw_default_route_with_default_controller - ActionController::Routing.with_controllers(['users']) do - set.draw do |map| - map.connect '/:controller/:action/:id', :controller => 'users' - end - assert_equal({:controller => 'users', :action => 'index'}, set.recognize_path('/')) + def test_route_with_parameter_shell + ActionController::Routing.with_controllers(['users', 'pages']) do + set.draw do |map| + map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/ + map.connect '/:controller/:action/:id' end - end - def test_route_with_parameter_shell - ActionController::Routing.with_controllers(['users', 'pages']) do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/ - map.connect '/:controller/:action/:id' - end + assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages')) + assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages/index')) + assert_equal({:controller => 'pages', :action => 'list'}, set.recognize_path('/pages/list')) - assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages')) - assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages/index')) - assert_equal({:controller => 'pages', :action => 'list'}, set.recognize_path('/pages/list')) + assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/pages/show/10')) + assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10')) + end + end - assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/pages/show/10')) - assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10')) + def test_route_requirements_with_anchor_chars_are_invalid + assert_raise ArgumentError do + set.draw do |map| + map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+/ end end - - def test_route_requirements_with_anchor_chars_are_invalid - assert_raises ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+/ - end + assert_raise ArgumentError do + set.draw do |map| + map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+/ end - assert_raises ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+/ - end + end + assert_raise ArgumentError do + set.draw do |map| + map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+$/ end - assert_raises ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+$/ - end + end + assert_raise ArgumentError do + set.draw do |map| + map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z/ end - assert_raises ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z/ - end + end + assert_raise ArgumentError do + set.draw do |map| + map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z/ end - assert_raises ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z/ - end + end + assert_nothing_raised do + set.draw do |map| + map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/, :name => /^(david|jamis)/ end - assert_nothing_raised do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/, :name => /^(david|jamis)/ - end - assert_raises ActionController::RoutingError do - set.generate :controller => 'pages', :action => 'show', :id => 10 - end + 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 - set.draw do |map| - map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :invalid} - end + def test_route_requirements_with_invalid_http_method_is_invalid + 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_head_method_condition_is_invalid - assert_raises ArgumentError do - set.draw do |map| - map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head} - 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_non_path_route_requirements_match_all + def test_route_requirements_with_head_method_condition_is_invalid + assert_raise ArgumentError do set.draw do |map| - 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 - set.generate(:controller => 'pages', :action => 'show', :name => 'not_jamis') - end - assert_raises ActionController::RoutingError do - set.generate(:controller => 'pages', :action => 'show', :name => 'nor_jamis_and_david') + map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head} end end + end - def test_recognize_with_encoded_id_and_regex - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /[a-zA-Z0-9\+]+/ - end + def test_non_path_route_requirements_match_all + set.draw do |map| + 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_raise ActionController::RoutingError do + set.generate(:controller => 'pages', :action => 'show', :name => 'not_jamis') + end + assert_raise ActionController::RoutingError do + set.generate(:controller => 'pages', :action => 'show', :name => 'nor_jamis_and_david') + end + end - assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10')) - assert_equal({:controller => 'pages', :action => 'show', :id => 'hello+world'}, set.recognize_path('/page/hello+world')) + def test_recognize_with_encoded_id_and_regex + set.draw do |map| + map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /[a-zA-Z0-9\+]+/ end - def test_recognize_with_conditions - Object.const_set(:PeopleController, Class.new) + assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10')) + assert_equal({:controller => 'pages', :action => 'show', :id => 'hello+world'}, set.recognize_path('/page/hello+world')) + end - set.draw do |map| - map.with_options(:controller => "people") do |people| - people.people "/people", :action => "index", :conditions => { :method => :get } - people.connect "/people", :action => "create", :conditions => { :method => :post } - people.person "/people/:id", :action => "show", :conditions => { :method => :get } - people.connect "/people/:id", :action => "update", :conditions => { :method => :put } - people.connect "/people/:id", :action => "destroy", :conditions => { :method => :delete } - end + def test_recognize_with_conditions + Object.const_set(:PeopleController, Class.new) + + set.draw do |map| + map.with_options(:controller => "people") do |people| + people.people "/people", :action => "index", :conditions => { :method => :get } + people.connect "/people", :action => "create", :conditions => { :method => :post } + people.person "/people/:id", :action => "show", :conditions => { :method => :get } + people.connect "/people/:id", :action => "update", :conditions => { :method => :put } + people.connect "/people/:id", :action => "destroy", :conditions => { :method => :delete } end + end + + request.path = "/people" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("index", request.path_parameters[:action]) + request.recycle! + + request.env["REQUEST_METHOD"] = "POST" + assert_nothing_raised { set.recognize(request) } + assert_equal("create", request.path_parameters[:action]) + request.recycle! + + request.env["REQUEST_METHOD"] = "PUT" + assert_nothing_raised { set.recognize(request) } + assert_equal("update", request.path_parameters[:action]) + request.recycle! + + assert_raise(ActionController::UnknownHttpMethod) { + request.env["REQUEST_METHOD"] = "BACON" + set.recognize(request) + } + request.recycle! + + request.path = "/people/5" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("show", request.path_parameters[:action]) + assert_equal("5", request.path_parameters[:id]) + request.recycle! + + request.env["REQUEST_METHOD"] = "PUT" + assert_nothing_raised { set.recognize(request) } + assert_equal("update", request.path_parameters[:action]) + assert_equal("5", request.path_parameters[:id]) + request.recycle! - request.path = "/people" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("index", request.path_parameters[:action]) - request.recycle! + request.env["REQUEST_METHOD"] = "DELETE" + assert_nothing_raised { set.recognize(request) } + assert_equal("destroy", request.path_parameters[:action]) + assert_equal("5", request.path_parameters[:id]) + request.recycle! + begin request.env["REQUEST_METHOD"] = "POST" - assert_nothing_raised { set.recognize(request) } - assert_equal("create", request.path_parameters[:action]) - request.recycle! - - request.env["REQUEST_METHOD"] = "PUT" - assert_nothing_raised { set.recognize(request) } - assert_equal("update", request.path_parameters[:action]) - request.recycle! - - assert_raises(ActionController::UnknownHttpMethod) { - request.env["REQUEST_METHOD"] = "BACON" - set.recognize(request) - } - request.recycle! - - request.path = "/people/5" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("show", request.path_parameters[:action]) - assert_equal("5", request.path_parameters[:id]) - request.recycle! - - request.env["REQUEST_METHOD"] = "PUT" - assert_nothing_raised { set.recognize(request) } - assert_equal("update", request.path_parameters[:action]) - assert_equal("5", request.path_parameters[:id]) - request.recycle! - - request.env["REQUEST_METHOD"] = "DELETE" - assert_nothing_raised { set.recognize(request) } - assert_equal("destroy", request.path_parameters[:action]) - assert_equal("5", request.path_parameters[:id]) - request.recycle! + set.recognize(request) + flunk 'Should have raised MethodNotAllowed' + rescue ActionController::MethodNotAllowed => e + assert_equal [:get, :put, :delete], e.allowed_methods + end + request.recycle! - begin - request.env["REQUEST_METHOD"] = "POST" - set.recognize(request) - flunk 'Should have raised MethodNotAllowed' - rescue ActionController::MethodNotAllowed => e - assert_equal [:get, :put, :delete], e.allowed_methods - end - request.recycle! + ensure + Object.send(:remove_const, :PeopleController) + end - ensure - Object.send(:remove_const, :PeopleController) + def test_recognize_with_alias_in_conditions + Object.const_set(:PeopleController, Class.new) + + set.draw do |map| + map.people "/people", :controller => 'people', :action => "index", + :conditions => { :method => :get } + map.root :people end - def test_recognize_with_alias_in_conditions - Object.const_set(:PeopleController, Class.new) + request.path = "/people" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("people", request.path_parameters[:controller]) + assert_equal("index", request.path_parameters[:action]) - set.draw do |map| - map.people "/people", :controller => 'people', :action => "index", - :conditions => { :method => :get } - map.root :people - end + request.path = "/" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("people", request.path_parameters[:controller]) + assert_equal("index", request.path_parameters[:action]) + ensure + Object.send(:remove_const, :PeopleController) + end - request.path = "/people" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("people", request.path_parameters[:controller]) - assert_equal("index", request.path_parameters[:action]) + def test_typo_recognition + Object.const_set(:ArticlesController, Class.new) - request.path = "/" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("people", request.path_parameters[:controller]) - assert_equal("index", request.path_parameters[:action]) - ensure - Object.send(:remove_const, :PeopleController) + set.draw do |map| + map.connect 'articles/:year/:month/:day/:title', + :controller => 'articles', :action => 'permalink', + :year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/ end - def test_typo_recognition - Object.const_set(:ArticlesController, Class.new) - - set.draw do |map| - map.connect 'articles/:year/:month/:day/:title', - :controller => 'articles', :action => 'permalink', - :year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/ - end + request.path = "/articles/2005/11/05/a-very-interesting-article" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("permalink", request.path_parameters[:action]) + assert_equal("2005", request.path_parameters[:year]) + assert_equal("11", request.path_parameters[:month]) + assert_equal("05", request.path_parameters[:day]) + assert_equal("a-very-interesting-article", request.path_parameters[:title]) - request.path = "/articles/2005/11/05/a-very-interesting-article" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("permalink", request.path_parameters[:action]) - assert_equal("2005", request.path_parameters[:year]) - assert_equal("11", request.path_parameters[:month]) - assert_equal("05", request.path_parameters[:day]) - assert_equal("a-very-interesting-article", request.path_parameters[:title]) + ensure + Object.send(:remove_const, :ArticlesController) + end - ensure - Object.send(:remove_const, :ArticlesController) + def test_routing_traversal_does_not_load_extra_classes + assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded" + set.draw do |map| + map.connect '/profile', :controller => 'profile' end - def test_routing_traversal_does_not_load_extra_classes - assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded" - set.draw do |map| - map.connect '/profile', :controller => 'profile' - end + request.path = '/profile' - request.path = '/profile' + set.recognize(request) rescue nil - set.recognize(request) rescue nil + assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded" + end + + def test_recognize_with_conditions_and_format + Object.const_set(:PeopleController, Class.new) - assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded" + set.draw do |map| + map.with_options(:controller => "people") do |people| + people.person "/people/:id", :action => "show", :conditions => { :method => :get } + people.connect "/people/:id", :action => "update", :conditions => { :method => :put } + people.connect "/people/:id.:_format", :action => "show", :conditions => { :method => :get } + end end - def test_recognize_with_conditions_and_format - Object.const_set(:PeopleController, Class.new) + request.path = "/people/5" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("show", request.path_parameters[:action]) + assert_equal("5", request.path_parameters[:id]) + request.recycle! - set.draw do |map| - map.with_options(:controller => "people") do |people| - people.person "/people/:id", :action => "show", :conditions => { :method => :get } - people.connect "/people/:id", :action => "update", :conditions => { :method => :put } - people.connect "/people/:id.:_format", :action => "show", :conditions => { :method => :get } - end - end + request.env["REQUEST_METHOD"] = "PUT" + assert_nothing_raised { set.recognize(request) } + assert_equal("update", request.path_parameters[:action]) + request.recycle! - request.path = "/people/5" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("show", request.path_parameters[:action]) - assert_equal("5", request.path_parameters[:id]) - request.recycle! - - request.env["REQUEST_METHOD"] = "PUT" - assert_nothing_raised { set.recognize(request) } - assert_equal("update", request.path_parameters[:action]) - request.recycle! - - request.path = "/people/5.png" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("show", request.path_parameters[:action]) - assert_equal("5", request.path_parameters[:id]) - assert_equal("png", request.path_parameters[:_format]) - ensure - Object.send(:remove_const, :PeopleController) - end - - def test_generate_with_default_action - set.draw do |map| - map.connect "/people", :controller => "people" - map.connect "/people/list", :controller => "people", :action => "list" - end + request.path = "/people/5.png" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("show", request.path_parameters[:action]) + assert_equal("5", request.path_parameters[:id]) + assert_equal("png", request.path_parameters[:_format]) + ensure + Object.send(:remove_const, :PeopleController) + end - url = set.generate(:controller => "people", :action => "list") - assert_equal "/people/list", url + def test_generate_with_default_action + set.draw do |map| + map.connect "/people", :controller => "people" + map.connect "/people/list", :controller => "people", :action => "list" end - def test_root_map - Object.const_set(:PeopleController, Class.new) + url = set.generate(:controller => "people", :action => "list") + assert_equal "/people/list", url + end - set.draw { |map| map.root :controller => "people" } + def test_root_map + Object.const_set(:PeopleController, Class.new) - request.path = "" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("people", request.path_parameters[:controller]) - assert_equal("index", request.path_parameters[:action]) - ensure - Object.send(:remove_const, :PeopleController) - end + set.draw { |map| map.root :controller => "people" } - def test_namespace - Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) }) + request.path = "" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("people", request.path_parameters[:controller]) + assert_equal("index", request.path_parameters[:action]) + ensure + Object.send(:remove_const, :PeopleController) + end - set.draw do |map| + def test_namespace + Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) }) - map.namespace 'api' do |api| - api.route 'inventory', :controller => "products", :action => 'inventory' - end + set.draw do |map| + map.namespace 'api' do |api| + api.route 'inventory', :controller => "products", :action => 'inventory' end - request.path = "/api/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_namespaced_root_map - Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) }) + request.path = "/api/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 - set.draw do |map| + def test_namespaced_root_map + Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) }) - map.namespace 'api' do |api| - api.root :controller => "products" - end + set.draw do |map| + map.namespace 'api' do |api| + api.root :controller => "products" end - request.path = "/api" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("api/products", request.path_parameters[:controller]) - assert_equal("index", request.path_parameters[:action]) - ensure - Object.send(:remove_const, :Api) end - def test_namespace_with_path_prefix - Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) }) - - set.draw do |map| + request.path = "/api" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("api/products", request.path_parameters[:controller]) + assert_equal("index", request.path_parameters[:action]) + ensure + Object.send(:remove_const, :Api) + end - map.namespace 'api', :path_prefix => 'prefix' do |api| - api.route 'inventory', :controller => "products", :action => 'inventory' - end + def test_namespace_with_path_prefix + 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 - - request.path = "/prefix/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" - map.connect "/ws/people", :controller => "people", :action => "index", :ws => true - end + request.path = "/prefix/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 - url = set.generate(:controller => "people", :action => "index", :ws => true) - assert_equal "/ws/people", url - end + def test_namespace_with_blank_path_prefix + Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) }) - def test_generate_changes_controller_module - set.draw { |map| map.connect ':controller/:action/:id' } - current = { :controller => "bling/bloop", :action => "bap", :id => 9 } - url = set.generate({:controller => "foo/bar", :action => "baz", :id => 7}, current) - assert_equal "/foo/bar/baz/7", url + set.draw do |map| + map.namespace 'api', :path_prefix => '' do |api| + api.route 'inventory', :controller => "products", :action => 'inventory' + end end - def test_id_is_not_impossibly_sticky - set.draw do |map| - map.connect 'foo/:number', :controller => "people", :action => "index" - map.connect ':controller/:action/:id' - 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 - url = set.generate({:controller => "people", :action => "index", :number => 3}, - {:controller => "people", :action => "index", :id => "21"}) - assert_equal "/foo/3", url + def test_generate_finds_best_fit + set.draw do |map| + map.connect "/people", :controller => "people", :action => "index" + map.connect "/ws/people", :controller => "people", :action => "index", :ws => true end - def test_id_is_sticky_when_it_ought_to_be - set.draw do |map| - map.connect ':controller/:id/:action' - end + url = set.generate(:controller => "people", :action => "index", :ws => true) + assert_equal "/ws/people", url + end - url = set.generate({:action => "destroy"}, {:controller => "people", :action => "show", :id => "7"}) - assert_equal "/people/7/destroy", url + def test_generate_changes_controller_module + set.draw { |map| map.connect ':controller/:action/:id' } + current = { :controller => "bling/bloop", :action => "bap", :id => 9 } + url = set.generate({:controller => "foo/bar", :action => "baz", :id => 7}, current) + assert_equal "/foo/bar/baz/7", url + end + + def test_id_is_not_impossibly_sticky + set.draw do |map| + map.connect 'foo/:number', :controller => "people", :action => "index" + map.connect ':controller/:action/:id' end - def test_use_static_path_when_possible - set.draw do |map| - map.connect 'about', :controller => "welcome", :action => "about" - map.connect ':controller/:action/:id' - end + url = set.generate({:controller => "people", :action => "index", :number => 3}, + {:controller => "people", :action => "index", :id => "21"}) + assert_equal "/foo/3", url + end - url = set.generate({:controller => "welcome", :action => "about"}, - {:controller => "welcome", :action => "get", :id => "7"}) - assert_equal "/about", url + def test_id_is_sticky_when_it_ought_to_be + set.draw do |map| + map.connect ':controller/:id/:action' end - def test_generate - set.draw { |map| map.connect ':controller/:action/:id' } + url = set.generate({:action => "destroy"}, {:controller => "people", :action => "show", :id => "7"}) + assert_equal "/people/7/destroy", url + end - args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" } - assert_equal "/foo/bar/7?x=y", set.generate(args) - assert_equal ["/foo/bar/7", [:x]], set.generate_extras(args) - assert_equal [:x], set.extra_keys(args) + def test_use_static_path_when_possible + set.draw do |map| + map.connect 'about', :controller => "welcome", :action => "about" + map.connect ':controller/:action/:id' end - def test_generate_with_path_prefix - set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => 'my' } + url = set.generate({:controller => "welcome", :action => "about"}, + {:controller => "welcome", :action => "get", :id => "7"}) + assert_equal "/about", url + end - args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" } - assert_equal "/my/foo/bar/7?x=y", set.generate(args) - end + def test_generate + set.draw { |map| map.connect ':controller/:action/:id' } - def test_named_routes_are_never_relative_to_modules - set.draw do |map| - map.connect "/connection/manage/:action", :controller => 'connection/manage' - map.connect "/connection/connection", :controller => "connection/connection" - map.family_connection "/connection", :controller => "connection" - end + args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" } + assert_equal "/foo/bar/7?x=y", set.generate(args) + assert_equal ["/foo/bar/7", [:x]], set.generate_extras(args) + assert_equal [:x], set.extra_keys(args) + end - url = set.generate({:controller => "connection"}, {:controller => 'connection/manage'}) - assert_equal "/connection/connection", url + def test_generate_with_path_prefix + set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => 'my' } - url = set.generate({:use_route => :family_connection, :controller => "connection"}, {:controller => 'connection/manage'}) - assert_equal "/connection", url - end + args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" } + assert_equal "/my/foo/bar/7?x=y", set.generate(args) + end - def test_action_left_off_when_id_is_recalled - set.draw do |map| - map.connect ':controller/:action/:id' - end - assert_equal '/post', set.generate( - {:controller => 'post', :action => 'index'}, - {:controller => 'post', :action => 'show', :id => '10'} - ) + 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' + map.connect "/connection/connection", :controller => "connection/connection" + map.family_connection "/connection", :controller => "connection" end - def test_query_params_will_be_shown_when_recalled - set.draw do |map| - map.connect 'show_post/:parameter', :controller => 'post', :action => 'show' - map.connect ':controller/:action/:id' - end - assert_equal '/post/edit?parameter=1', set.generate( - {:action => 'edit', :parameter => 1}, - {:controller => 'post', :action => 'show', :parameter => 1} - ) + url = set.generate({:controller => "connection"}, {:controller => 'connection/manage'}) + assert_equal "/connection/connection", url + + url = set.generate({:use_route => :family_connection, :controller => "connection"}, {:controller => 'connection/manage'}) + assert_equal "/connection", url + end + + def test_action_left_off_when_id_is_recalled + set.draw do |map| + map.connect ':controller/:action/:id' end + assert_equal '/post', set.generate( + {:controller => 'post', :action => 'index'}, + {:controller => 'post', :action => 'show', :id => '10'} + ) + 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( - {:action => 'show', :project_id => 1}, - {:controller => 'post', :action => 'show', :project_id => '1'}) + def test_query_params_will_be_shown_when_recalled + set.draw do |map| + map.connect 'show_post/:parameter', :controller => 'post', :action => 'show' + map.connect ':controller/:action/:id' end + assert_equal '/post/edit?parameter=1', set.generate( + {:action => 'edit', :parameter => 1}, + {:controller => 'post', :action => 'show', :parameter => 1} + ) + end - def test_generate_all - set.draw do |map| - map.connect 'show_post/:id', :controller => 'post', :action => 'show' - map.connect ':controller/:action/:id' - end - all = set.generate( - {:action => 'show', :id => 10, :generate_all => true}, - {:controller => 'post', :action => 'show'} - ) - assert_equal 2, all.length - assert_equal '/show_post/10', all.first - assert_equal '/post/show/10', all.last + def test_format_is_not_inherit + set.draw do |map| + map.connect '/posts.:format', :controller => 'posts' end - def test_named_route_in_nested_resource - set.draw do |map| - map.resources :projects do |project| - project.milestones 'milestones', :controller => 'milestones', :action => 'index' - end - end + assert_equal '/posts', set.generate( + {:controller => 'posts'}, + {:controller => 'posts', :action => 'index', :format => 'xml'} + ) - request.path = "/projects/1/milestones" - request.env["REQUEST_METHOD"] = "GET" - assert_nothing_raised { set.recognize(request) } - assert_equal("milestones", request.path_parameters[:controller]) - assert_equal("index", request.path_parameters[:action]) - end + assert_equal '/posts.xml', set.generate( + {:controller => 'posts', :format => 'xml'}, + {:controller => 'posts', :action => 'index', :format => 'xml'} + ) + end - def test_setting_root_in_namespace_using_symbol - assert_nothing_raised do - set.draw do |map| - map.namespace :admin do |admin| - admin.root :controller => 'home' - end - end - 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( + {:action => 'show', :project_id => 1}, + {:controller => 'post', :action => 'show', :project_id => '1'}) + end + + def test_generate_all + set.draw do |map| + map.connect 'show_post/:id', :controller => 'post', :action => 'show' + map.connect ':controller/:action/:id' end + all = set.generate( + {:action => 'show', :id => 10, :generate_all => true}, + {:controller => 'post', :action => 'show'} + ) + assert_equal 2, all.length + assert_equal '/show_post/10', all.first + assert_equal '/post/show/10', all.last + end - def test_setting_root_in_namespace_using_string - assert_nothing_raised do - set.draw do |map| - map.namespace 'admin' do |admin| - admin.root :controller => 'home' - end - end + def test_named_route_in_nested_resource + set.draw do |map| + map.resources :projects do |project| + project.milestones 'milestones', :controller => 'milestones', :action => 'index' end end - def test_route_requirements_with_unsupported_regexp_options_must_error - assert_raises ArgumentError do - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => /(david|jamis)/m} + request.path = "/projects/1/milestones" + request.env["REQUEST_METHOD"] = "GET" + assert_nothing_raised { set.recognize(request) } + assert_equal("milestones", request.path_parameters[:controller]) + assert_equal("index", request.path_parameters[:action]) + end + + def test_setting_root_in_namespace_using_symbol + assert_nothing_raised do + set.draw do |map| + map.namespace :admin do |admin| + admin.root :controller => 'home' end end end + end - def test_route_requirements_with_supported_options_must_not_error - assert_nothing_raised do - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => /(david|jamis)/i} - end - end - assert_nothing_raised do - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp - ( #Either - david #The Creator - | #Or - jamis #The Deployer - )/x} + def test_setting_root_in_namespace_using_string + assert_nothing_raised do + set.draw do |map| + map.namespace 'admin' do |admin| + admin.root :controller => 'home' end end end + end - def test_route_requirement_recognize_with_ignore_case + def test_route_requirements_with_unsupported_regexp_options_must_error + assert_raise ArgumentError do set.draw do |map| map.connect 'page/:name', :controller => 'pages', :action => 'show', - :requirements => {:name => /(david|jamis)/i} + :requirements => {:name => /(david|jamis)/m} end - assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis')) - assert_raises ActionController::RoutingError do - set.recognize_path('/page/davidjamis') - end - assert_equal({:controller => 'pages', :action => 'show', :name => 'DAVID'}, set.recognize_path('/page/DAVID')) end + end - def test_route_requirement_generate_with_ignore_case + def test_route_requirements_with_supported_options_must_not_error + assert_nothing_raised do set.draw do |map| map.connect 'page/:name', :controller => 'pages', :action => 'show', :requirements => {:name => /(david|jamis)/i} end - url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'}) - assert_equal "/page/david", url - assert_raises ActionController::RoutingError do - url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'}) - end - url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) - assert_equal "/page/JAMIS", url end - - def test_route_requirement_recognize_with_extended_syntax + assert_nothing_raised do set.draw do |map| map.connect 'page/:name', :controller => 'pages', :action => 'show', @@ -2330,142 +2375,183 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do jamis #The Deployer )/x} 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 - set.recognize_path('/page/david #The Creator') - end - assert_raises ActionController::RoutingError do - set.recognize_path('/page/David') - end end + end - def test_route_requirement_generate_with_extended_syntax - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp - ( #Either - david #The Creator - | #Or - jamis #The Deployer - )/x} - end - url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'}) - assert_equal "/page/david", url - assert_raises ActionController::RoutingError do - url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'}) - end - assert_raises ActionController::RoutingError do - url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) - end + def test_route_requirement_recognize_with_ignore_case + set.draw do |map| + map.connect 'page/:name', :controller => 'pages', + :action => 'show', + :requirements => {:name => /(david|jamis)/i} end + assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis')) + assert_raise ActionController::RoutingError do + set.recognize_path('/page/davidjamis') + end + assert_equal({:controller => 'pages', :action => 'show', :name => 'DAVID'}, set.recognize_path('/page/DAVID')) + end - def test_route_requirement_generate_with_xi_modifiers - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp - ( #Either - david #The Creator - | #Or - jamis #The Deployer - )/xi} - end - url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) - assert_equal "/page/JAMIS", url + def test_route_requirement_generate_with_ignore_case + set.draw do |map| + map.connect 'page/:name', :controller => 'pages', + :action => 'show', + :requirements => {:name => /(david|jamis)/i} + end + url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'}) + assert_equal "/page/david", url + assert_raise ActionController::RoutingError do + url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'}) end + url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) + assert_equal "/page/JAMIS", url + end - def test_route_requirement_recognize_with_xi_modifiers - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp - ( #Either - david #The Creator - | #Or - jamis #The Deployer - )/xi} - end - assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'}, set.recognize_path('/page/JAMIS')) + def test_route_requirement_recognize_with_extended_syntax + set.draw do |map| + map.connect 'page/:name', :controller => 'pages', + :action => 'show', + :requirements => {:name => / # Desperately overcommented regexp + ( #Either + david #The Creator + | #Or + jamis #The Deployer + )/x} + 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_raise ActionController::RoutingError do + set.recognize_path('/page/david #The Creator') + end + assert_raise ActionController::RoutingError do + set.recognize_path('/page/David') end end - class RouteLoadingTest < Test::Unit::TestCase - def setup - routes.instance_variable_set '@routes_last_modified', nil - silence_warnings { Object.const_set :RAILS_ROOT, '.' } - routes.add_configuration_file(File.join(RAILS_ROOT, 'config', 'routes.rb')) + def test_route_requirement_generate_with_extended_syntax + set.draw do |map| + map.connect 'page/:name', :controller => 'pages', + :action => 'show', + :requirements => {:name => / # Desperately overcommented regexp + ( #Either + david #The Creator + | #Or + jamis #The Deployer + )/x} + end + url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'}) + assert_equal "/page/david", url + assert_raise ActionController::RoutingError do + url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'}) + end + assert_raise ActionController::RoutingError do + url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) + end + end - @stat = stub_everything + def test_route_requirement_generate_with_xi_modifiers + set.draw do |map| + map.connect 'page/:name', :controller => 'pages', + :action => 'show', + :requirements => {:name => / # Desperately overcommented regexp + ( #Either + david #The Creator + | #Or + jamis #The Deployer + )/xi} end + url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) + assert_equal "/page/JAMIS", url + end - def teardown - ActionController::Routing::Routes.configuration_files.clear - Object.send :remove_const, :RAILS_ROOT + def test_route_requirement_recognize_with_xi_modifiers + set.draw do |map| + map.connect 'page/:name', :controller => 'pages', + :action => 'show', + :requirements => {:name => / # Desperately overcommented regexp + ( #Either + david #The Creator + | #Or + jamis #The Deployer + )/xi} end + assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'}, set.recognize_path('/page/JAMIS')) + end +end - def test_load - File.expects(:stat).returns(@stat) - routes.expects(:load).with(regexp_matches(/routes\.rb$/)) +class RouteLoadingTest < Test::Unit::TestCase + def setup + routes.instance_variable_set '@routes_last_modified', nil + silence_warnings { Object.const_set :RAILS_ROOT, '.' } + routes.add_configuration_file(File.join(RAILS_ROOT, 'config', 'routes.rb')) - routes.reload - end + @stat = stub_everything + end - def test_no_reload_when_not_modified - @stat.expects(:mtime).times(2).returns(1) - File.expects(:stat).times(2).returns(@stat) - routes.expects(:load).with(regexp_matches(/routes\.rb$/)).at_most_once + def teardown + ActionController::Routing::Routes.configuration_files.clear + Object.send :remove_const, :RAILS_ROOT + end - 2.times { routes.reload } - end + def test_load + File.expects(:stat).returns(@stat) + routes.expects(:load).with(regexp_matches(/routes\.rb$/)) - def test_reload_when_modified - @stat.expects(:mtime).at_least(2).returns(1, 2) - File.expects(:stat).at_least(2).returns(@stat) - routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2) + routes.reload + end - 2.times { routes.reload } - end + def test_no_reload_when_not_modified + @stat.expects(:mtime).times(2).returns(1) + File.expects(:stat).times(2).returns(@stat) + routes.expects(:load).with(regexp_matches(/routes\.rb$/)).at_most_once - def test_bang_forces_reload - @stat.expects(:mtime).at_least(2).returns(1) - File.expects(:stat).at_least(2).returns(@stat) - routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2) + 2.times { routes.reload } + end - 2.times { routes.reload! } - end + def test_reload_when_modified + @stat.expects(:mtime).at_least(2).returns(1, 2) + File.expects(:stat).at_least(2).returns(@stat) + routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2) - def test_adding_inflections_forces_reload - ActiveSupport::Inflector::Inflections.instance.expects(:uncountable).with('equipment') - routes.expects(:reload!) + 2.times { routes.reload } + end - ActiveSupport::Inflector.inflections { |inflect| inflect.uncountable('equipment') } - end + def test_bang_forces_reload + @stat.expects(:mtime).at_least(2).returns(1) + File.expects(:stat).at_least(2).returns(@stat) + routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2) - def test_load_with_configuration - routes.configuration_files.clear - routes.add_configuration_file("foobarbaz") - File.expects(:stat).returns(@stat) - routes.expects(:load).with("foobarbaz") + 2.times { routes.reload! } + end - routes.reload - end - - def test_load_multiple_configurations - routes.add_configuration_file("engines.rb") - - File.expects(:stat).at_least_once.returns(@stat) + def test_adding_inflections_forces_reload + ActiveSupport::Inflector::Inflections.instance.expects(:uncountable).with('equipment') + routes.expects(:reload!) - routes.expects(:load).with('./config/routes.rb') - routes.expects(:load).with('engines.rb') + ActiveSupport::Inflector.inflections { |inflect| inflect.uncountable('equipment') } + end - routes.reload - end + def test_load_with_configuration + routes.configuration_files.clear + routes.add_configuration_file("foobarbaz") + File.expects(:stat).returns(@stat) + routes.expects(:load).with("foobarbaz") - private - def routes - ActionController::Routing::Routes - end + routes.reload + end + + def test_load_multiple_configurations + routes.add_configuration_file("engines.rb") + + File.expects(:stat).at_least_once.returns(@stat) + + routes.expects(:load).with('./config/routes.rb') + routes.expects(:load).with('engines.rb') + + routes.reload end + + private + def routes + ActionController::Routing::Routes + 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 b703f340a0..2e14a0a32c 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -44,12 +44,12 @@ class SendFileTest < ActionController::TestCase response = nil assert_nothing_raised { response = process('file') } assert_not_nil response - assert_kind_of Proc, response.body + assert_kind_of Proc, response.body_parts require 'stringio' output = StringIO.new output.binmode - assert_nothing_raised { response.body.call(response, output) } + assert_nothing_raised { response.body_parts.call(response, output) } assert_equal file_data, output.string end @@ -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/session/cookie_store_test.rb b/actionpack/test/controller/session/cookie_store_test.rb index b48a8c3830..9b3f9afb0d 100644 --- a/actionpack/test/controller/session/cookie_store_test.rb +++ b/actionpack/test/controller/session/cookie_store_test.rb @@ -24,13 +24,17 @@ class CookieStoreTest < ActionController::IntegrationTest def set_session_value session[:foo] = "bar" - render :text => Verifier.generate(session.to_hash) + render :text => Rack::Utils.escape(Verifier.generate(session.to_hash)) end def get_session_value render :text => "foo: #{session[:foo].inspect}" end + def get_session_id + render :text => "foo: #{session[:foo].inspect}; id: #{request.session_options[:id]}" + end + def call_reset_session reset_session head :ok @@ -93,7 +97,7 @@ class CookieStoreTest < ActionController::IntegrationTest with_test_route_set do get '/set_session_value' assert_response :success - assert_equal ["_myapp_session=#{response.body}; path=/; httponly"], + assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly", headers['Set-Cookie'] end end @@ -107,6 +111,20 @@ class CookieStoreTest < ActionController::IntegrationTest end end + def test_getting_session_id + with_test_route_set do + cookies[SessionKey] = SignedBar + get '/persistent_session_id' + assert_response :success + assert_equal response.body.size, 32 + session_id = response.body + + get '/get_session_id' + assert_response :success + assert_equal "foo: \"bar\"; id: #{session_id}", response.body + end + end + def test_disregards_tampered_sessions with_test_route_set do cookies[SessionKey] = "BAh7BjoIZm9vIghiYXI%3D--123456780" @@ -128,7 +146,7 @@ class CookieStoreTest < ActionController::IntegrationTest with_test_route_set do get '/no_session_access' assert_response :success - assert_equal [], headers['Set-Cookie'] + assert_equal "", headers['Set-Cookie'] end end @@ -138,7 +156,7 @@ class CookieStoreTest < ActionController::IntegrationTest "fef868465920f415f2c0652d6910d3af288a0367" get '/no_session_access' assert_response :success - assert_equal [], headers['Set-Cookie'] + assert_equal "", headers['Set-Cookie'] end end @@ -147,7 +165,7 @@ class CookieStoreTest < ActionController::IntegrationTest get '/set_session_value' assert_response :success session_payload = response.body - assert_equal ["_myapp_session=#{response.body}; path=/; httponly"], + assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly", headers['Set-Cookie'] get '/call_reset_session' @@ -192,7 +210,8 @@ class CookieStoreTest < ActionController::IntegrationTest assert_response :success cookie_body = response.body - assert_equal ["_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; httponly"], headers['Set-Cookie'] + assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly", + headers['Set-Cookie'] # Second request does not access the session time = Time.local(2008, 4, 25) @@ -202,7 +221,8 @@ class CookieStoreTest < ActionController::IntegrationTest get '/no_session_access' assert_response :success - assert_equal ["_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; httponly"], headers['Set-Cookie'] + assert_equal "_myapp_session=#{cookie_body}; path=/; expires=#{expected_expiry}; HttpOnly", + headers['Set-Cookie'] end end @@ -217,4 +237,13 @@ class CookieStoreTest < ActionController::IntegrationTest yield end end + + def unmarshal_session(cookie_string) + session = Rack::Utils.parse_query(cookie_string, ';,').inject({}) {|h,(k,v)| + h[k] = Array === v ? v.first : v + h + }[SessionKey] + verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1') + verifier.verify(session) + end end diff --git a/actionpack/test/controller/session/mem_cache_store_test.rb b/actionpack/test/controller/session/mem_cache_store_test.rb index 2e2bf79148..7561c93e4a 100644 --- a/actionpack/test/controller/session/mem_cache_store_test.rb +++ b/actionpack/test/controller/session/mem_cache_store_test.rb @@ -16,8 +16,15 @@ class MemCacheStoreTest < ActionController::IntegrationTest render :text => "foo: #{session[:foo].inspect}" end + def get_session_id + session[:foo] + render :text => "#{request.session_options[:id]}" + end + def call_reset_session + session[:bar] reset_session + session[:bar] = "baz" head :ok end @@ -50,38 +57,56 @@ class MemCacheStoreTest < ActionController::IntegrationTest with_test_route_set do get '/get_session_value' assert_response :success - assert_equal 'foo: nil', response.body + assert_equal 'foo: nil', response.body end end - def test_prevents_session_fixation + def test_setting_session_value_after_session_reset with_test_route_set do - get '/get_session_value' + get '/set_session_value' assert_response :success - assert_equal 'foo: nil', response.body + assert cookies['_session_id'] session_id = cookies['_session_id'] - reset! + get '/call_reset_session' + assert_response :success + assert_not_equal [], headers['Set-Cookie'] - get '/set_session_value', :_session_id => session_id + get '/get_session_value' assert_response :success - assert_equal nil, cookies['_session_id'] + assert_equal 'foo: nil', response.body + + get '/get_session_id' + assert_response :success + assert_not_equal session_id, response.body end end - def test_setting_session_value_after_session_reset + def test_getting_session_id with_test_route_set do get '/set_session_value' assert_response :success assert cookies['_session_id'] + session_id = cookies['_session_id'] - get '/call_reset_session' + get '/get_session_id' assert_response :success - assert_not_equal [], headers['Set-Cookie'] + assert_equal session_id, response.body + end + end + def test_prevents_session_fixation + with_test_route_set do get '/get_session_value' assert_response :success assert_equal 'foo: nil', response.body + session_id = cookies['_session_id'] + + reset! + + get '/set_session_value', :_session_id => session_id + assert_response :success + assert_equal nil, cookies['_session_id'] end end rescue LoadError, RuntimeError diff --git a/actionpack/test/controller/session/test_session_test.rb b/actionpack/test/controller/session/test_session_test.rb index 83103be3ec..de6539e1cc 100644 --- a/actionpack/test/controller/session/test_session_test.rb +++ b/actionpack/test/controller/session/test_session_test.rb @@ -33,7 +33,7 @@ class ActionController::TestSessionTest < ActiveSupport::TestCase assert_equal('value', session[:key]) end - def test_calling_delete_removes item + def test_calling_delete_removes_item session = ActionController::TestSession.new session[:key] = 'value' assert_equal('value', session[:key]) diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index 55b59d9401..124e259ef6 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -517,6 +517,14 @@ XML assert_nil @request.instance_variable_get("@request_method") end + def test_params_reset_after_post_request + post :no_op, :foo => "bar" + assert_equal "bar", @request.params[:foo] + @request.recycle! + post :no_op + assert @request.params[:foo].blank? + end + %w(controller response request).each do |variable| %w(get post put delete head process).each do |method| define_method("test_#{variable}_missing_for_#{method}_raises_error") do 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/dispatch/middleware_stack_test.rb b/actionpack/test/dispatch/middleware_stack_test.rb index e5496c848b..f4e18308ae 100644 --- a/actionpack/test/dispatch/middleware_stack_test.rb +++ b/actionpack/test/dispatch/middleware_stack_test.rb @@ -73,4 +73,18 @@ class MiddlewareStackTest < ActiveSupport::TestCase end end end + + test "lazy evaluates middleware class" do + assert_difference "@stack.size" do + @stack.use lambda { BazMiddleware } + end + assert_equal BazMiddleware, @stack.last.klass + end + + test "lazy evaluates middleware arguments" do + assert_difference "@stack.size" do + @stack.use BazMiddleware, lambda { :foo } + end + assert_equal [:foo], @stack.last.send(:build_args) + end end diff --git a/actionpack/test/dispatch/rack_test.rb b/actionpack/test/dispatch/rack_test.rb index 92e6f163b2..9fad4b22ee 100644 --- a/actionpack/test/dispatch/rack_test.rb +++ b/actionpack/test/dispatch/rack_test.rb @@ -218,7 +218,7 @@ class RackResponseTest < BaseRackTest "Content-Type" => "text/html; charset=utf-8", "Cache-Control" => "private, max-age=0, must-revalidate", "ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"', - "Set-Cookie" => [], + "Set-Cookie" => "", "Content-Length" => "13" }, headers) @@ -227,7 +227,22 @@ class RackResponseTest < BaseRackTest assert_equal ["Hello, World!"], parts end - test "streaming block" do + def test_utf8_output + @response.body = [1090, 1077, 1089, 1090].pack("U*") + @response.prepare! + + status, headers, body = @response.to_a + assert_equal 200, status + assert_equal({ + "Content-Type" => "text/html; charset=utf-8", + "Cache-Control" => "private, max-age=0, must-revalidate", + "ETag" => '"ebb5e89e8a94e9dd22abf5d915d112b2"', + "Set-Cookie" => "", + "Content-Length" => "8" + }, headers) + end + + def test_streaming_block @response.body = Proc.new do |response, output| 5.times { |n| output.write(n) } end @@ -237,13 +252,12 @@ class RackResponseTest < BaseRackTest assert_equal 200, status assert_equal({ "Content-Type" => "text/html; charset=utf-8", - "Content-Length" => "", "Cache-Control" => "no-cache", - "Set-Cookie" => [] + "Set-Cookie" => "" }, headers) parts = [] - body.each { |part| parts << part } + body.each { |part| parts << part.to_s } assert_equal ["0", "1", "2", "3", "4"], parts end end diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb index 5b9728cc42..2f409f020d 100644 --- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb @@ -103,7 +103,7 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest test "does not create tempfile if no file has been selected" do params = parse_multipart('none') - assert_equal %w(files submit-name), params.keys.sort + assert_equal %w(submit-name), params.keys.sort assert_equal 'Larry', params['submit-name'] assert_equal nil, params['files'] end diff --git a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb index 9f0535bbcc..51a660f614 100644 --- a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb @@ -80,36 +80,6 @@ class UrlEncodedParamsParsingTest < ActionController::IntegrationTest assert_parses expected, query end - test "parses params with non alphanumeric name" do - query = "a/b[c]=d" - expected = { "a/b" => { "c" => "d" }} - assert_parses expected, query - end - - test "parses params with single brackets in the middle" do - query = "a/b[c]d=e" - expected = { "a/b" => {} } - assert_parses expected, query - end - - test "parses params with separated brackets" do - query = "a/b@[c]d[e]=f" - expected = { "a/b@" => { }} - assert_parses expected, query - end - - test "parses params with separated brackets and array" do - query = "a/b@[c]d[e][]=f" - expected = { "a/b@" => { }} - assert_parses expected, query - end - - test "parses params with unmatched brackets and array" do - query = "a/b@[c][d[e][]=f" - expected = { "a/b@" => { "c" => { }}} - assert_parses expected, query - end - test "parses params with nil key" do query = "=&test2=value1" expected = { "test2" => "value1" } @@ -156,12 +126,6 @@ class UrlEncodedParamsParsingTest < ActionController::IntegrationTest assert_parses expected, query end - test "parses params with Prototype's hack around Safari 2 trailing null character" do - query = "selected[]=1&selected[]=2&selected[]=3&_=" - expected = { "selected" => [ "1", "2", "3" ] } - assert_parses expected, query - end - test "passes through rack middleware and parses params" do with_muck_middleware do assert_parses({ "a" => { "b" => "c" } }, "a[b]=c") diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index f1e052ff17..d57a2a611f 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -3,7 +3,6 @@ require 'abstract_unit' class RequestTest < ActiveSupport::TestCase def setup ActionController::Base.relative_url_root = nil - @request = ActionController::TestRequest.new end def teardown @@ -11,60 +10,52 @@ class RequestTest < ActiveSupport::TestCase end test "remote ip" do - assert_equal '0.0.0.0', @request.remote_ip + request = stub_request 'REMOTE_ADDR' => '1.2.3.4' + assert_equal '1.2.3.4', request.remote_ip - @request.remote_addr = '1.2.3.4' - assert_equal '1.2.3.4', @request.remote_ip + request = stub_request 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6' + assert_equal '1.2.3.4', request.remote_ip - @request.remote_addr = '1.2.3.4,3.4.5.6' - assert_equal '1.2.3.4', @request.remote_ip + request = stub_request 'REMOTE_ADDR' => '1.2.3.4', + 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' + assert_equal '1.2.3.4', request.remote_ip - @request.env['HTTP_CLIENT_IP'] = '2.3.4.5' - assert_equal '1.2.3.4', @request.remote_ip + request = stub_request 'REMOTE_ADDR' => '127.0.0.1', + 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' + assert_equal '3.4.5.6', request.remote_ip - @request.remote_addr = '192.168.0.1' - assert_equal '2.3.4.5', @request.remote_ip - @request.env.delete 'HTTP_CLIENT_IP' + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,3.4.5.6' + assert_equal '3.4.5.6', request.remote_ip - @request.remote_addr = '1.2.3.4' - @request.env['HTTP_X_FORWARDED_FOR'] = '3.4.5.6' - assert_equal '1.2.3.4', @request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '172.16.0.1,3.4.5.6' + assert_equal '3.4.5.6', request.remote_ip - @request.remote_addr = '127.0.0.1' - @request.env['HTTP_X_FORWARDED_FOR'] = '3.4.5.6' - assert_equal '3.4.5.6', @request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '192.168.0.1,3.4.5.6' + assert_equal '3.4.5.6', request.remote_ip - @request.env['HTTP_X_FORWARDED_FOR'] = 'unknown,3.4.5.6' - assert_equal '3.4.5.6', @request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1,3.4.5.6' + assert_equal '3.4.5.6', request.remote_ip - @request.env['HTTP_X_FORWARDED_FOR'] = '172.16.0.1,3.4.5.6' - assert_equal '3.4.5.6', @request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 10.0.0.1, 3.4.5.6' + assert_equal '3.4.5.6', request.remote_ip - @request.env['HTTP_X_FORWARDED_FOR'] = '192.168.0.1,3.4.5.6' - assert_equal '3.4.5.6', @request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '127.0.0.1,3.4.5.6' + assert_equal '3.4.5.6', request.remote_ip - @request.env['HTTP_X_FORWARDED_FOR'] = '10.0.0.1,3.4.5.6' - assert_equal '3.4.5.6', @request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1' + assert_equal 'unknown', request.remote_ip - @request.env['HTTP_X_FORWARDED_FOR'] = '10.0.0.1, 10.0.0.1, 3.4.5.6' - assert_equal '3.4.5.6', @request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4' + assert_equal '3.4.5.6', request.remote_ip - @request.env['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,3.4.5.6' - assert_equal '3.4.5.6', @request.remote_ip - - @request.env['HTTP_X_FORWARDED_FOR'] = 'unknown,192.168.0.1' - assert_equal 'unknown', @request.remote_ip - - @request.env['HTTP_X_FORWARDED_FOR'] = '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4' - assert_equal '3.4.5.6', @request.remote_ip - - @request.env['HTTP_CLIENT_IP'] = '8.8.8.8' - e = assert_raises(ActionController::ActionControllerError) { - @request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', + 'HTTP_CLIENT_IP' => '2.2.2.2' + e = assert_raise(ActionController::ActionControllerError) { + request.remote_ip } assert_match /IP spoofing attack/, e.message - assert_match /HTTP_X_FORWARDED_FOR="9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4"/, e.message - assert_match /HTTP_CLIENT_IP="8.8.8.8"/, e.message + assert_match /HTTP_X_FORWARDED_FOR="1.1.1.1"/, e.message + assert_match /HTTP_CLIENT_IP="2.2.2.2"/, e.message # turn IP Spoofing detection off. # This is useful for sites that are aimed at non-IP clients. The typical @@ -72,338 +63,343 @@ class RequestTest < ActiveSupport::TestCase # leap of faith to assume that their proxies are ever going to set the # HTTP_CLIENT_IP/HTTP_X_FORWARDED_FOR headers properly. ActionController::Base.ip_spoofing_check = false - assert_equal('8.8.8.8', @request.remote_ip) + request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', + 'HTTP_CLIENT_IP' => '2.2.2.2' + assert_equal '2.2.2.2', request.remote_ip ActionController::Base.ip_spoofing_check = true - @request.env['HTTP_X_FORWARDED_FOR'] = '8.8.8.8, 9.9.9.9' - assert_equal '8.8.8.8', @request.remote_ip - - @request.env.delete 'HTTP_CLIENT_IP' - @request.env.delete 'HTTP_X_FORWARDED_FOR' + request = stub_request 'HTTP_X_FORWARDED_FOR' => '8.8.8.8, 9.9.9.9' + assert_equal '9.9.9.9', request.remote_ip end test "domains" do - @request.host = "www.rubyonrails.org" - assert_equal "rubyonrails.org", @request.domain + request = stub_request 'HTTP_HOST' => 'www.rubyonrails.org' + assert_equal "rubyonrails.org", request.domain - @request.host = "www.rubyonrails.co.uk" - assert_equal "rubyonrails.co.uk", @request.domain(2) + request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk" + assert_equal "rubyonrails.co.uk", request.domain(2) - @request.host = "192.168.1.200" - assert_nil @request.domain + request = stub_request 'HTTP_HOST' => "192.168.1.200" + assert_nil request.domain - @request.host = "foo.192.168.1.200" - assert_nil @request.domain + request = stub_request 'HTTP_HOST' => "foo.192.168.1.200" + assert_nil request.domain - @request.host = "192.168.1.200.com" - assert_equal "200.com", @request.domain - - @request.host = nil - assert_nil @request.domain + request = stub_request 'HTTP_HOST' => "192.168.1.200.com" + assert_equal "200.com", request.domain end test "subdomains" do - @request.host = "www.rubyonrails.org" - assert_equal %w( www ), @request.subdomains + request = stub_request 'HTTP_HOST' => "www.rubyonrails.org" + assert_equal %w( www ), request.subdomains - @request.host = "www.rubyonrails.co.uk" - assert_equal %w( www ), @request.subdomains(2) + request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk" + assert_equal %w( www ), request.subdomains(2) - @request.host = "dev.www.rubyonrails.co.uk" - assert_equal %w( dev www ), @request.subdomains(2) + request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk" + assert_equal %w( dev www ), request.subdomains(2) - @request.host = "foobar.foobar.com" - assert_equal %w( foobar ), @request.subdomains + request = stub_request 'HTTP_HOST' => "foobar.foobar.com" + assert_equal %w( foobar ), request.subdomains - @request.host = "192.168.1.200" - assert_equal [], @request.subdomains + request = stub_request 'HTTP_HOST' => "192.168.1.200" + assert_equal [], request.subdomains - @request.host = "foo.192.168.1.200" - assert_equal [], @request.subdomains + request = stub_request 'HTTP_HOST' => "foo.192.168.1.200" + assert_equal [], request.subdomains - @request.host = "192.168.1.200.com" - assert_equal %w( 192 168 1 ), @request.subdomains + request = stub_request 'HTTP_HOST' => "192.168.1.200.com" + assert_equal %w( 192 168 1 ), request.subdomains - @request.host = nil - assert_equal [], @request.subdomains + request = stub_request 'HTTP_HOST' => nil + assert_equal [], request.subdomains end test "port string" do - @request.port = 80 - assert_equal "", @request.port_string + request = stub_request 'HTTP_HOST' => 'www.example.org:80' + assert_equal "", request.port_string - @request.port = 8080 - assert_equal ":8080", @request.port_string + request = stub_request 'HTTP_HOST' => 'www.example.org:8080' + assert_equal ":8080", request.port_string end test "request uri" do - @request.env['SERVER_SOFTWARE'] = 'Apache 42.342.3432' - - @request.set_REQUEST_URI "http://www.rubyonrails.org/path/of/some/uri?mapped=1" - assert_equal "/path/of/some/uri?mapped=1", @request.request_uri - assert_equal "/path/of/some/uri", @request.path + request = stub_request 'REQUEST_URI' => "http://www.rubyonrails.org/path/of/some/uri?mapped=1" + assert_equal "/path/of/some/uri?mapped=1", request.request_uri + assert_equal "/path/of/some/uri", request.path - @request.set_REQUEST_URI "http://www.rubyonrails.org/path/of/some/uri" - assert_equal "/path/of/some/uri", @request.request_uri - assert_equal "/path/of/some/uri", @request.path + request = stub_request 'REQUEST_URI' => "http://www.rubyonrails.org/path/of/some/uri" + assert_equal "/path/of/some/uri", request.request_uri + assert_equal "/path/of/some/uri", request.path - @request.set_REQUEST_URI "/path/of/some/uri" - assert_equal "/path/of/some/uri", @request.request_uri - assert_equal "/path/of/some/uri", @request.path + request = stub_request 'REQUEST_URI' => "/path/of/some/uri" + assert_equal "/path/of/some/uri", request.request_uri + assert_equal "/path/of/some/uri", request.path - @request.set_REQUEST_URI "/" - assert_equal "/", @request.request_uri - assert_equal "/", @request.path + request = stub_request 'REQUEST_URI' => "/" + assert_equal "/", request.request_uri + assert_equal "/", request.path - @request.set_REQUEST_URI "/?m=b" - assert_equal "/?m=b", @request.request_uri - assert_equal "/", @request.path + request = stub_request 'REQUEST_URI' => "/?m=b" + assert_equal "/?m=b", request.request_uri + assert_equal "/", request.path - @request.set_REQUEST_URI "/" - @request.env['SCRIPT_NAME'] = "/dispatch.cgi" - assert_equal "/", @request.request_uri - assert_equal "/", @request.path + request = stub_request 'REQUEST_URI' => "/", 'SCRIPT_NAME' => '/dispatch.cgi' + assert_equal "/", request.request_uri + assert_equal "/", request.path ActionController::Base.relative_url_root = "/hieraki" - @request.set_REQUEST_URI "/hieraki/" - @request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi" - assert_equal "/hieraki/", @request.request_uri - assert_equal "/", @request.path + request = stub_request 'REQUEST_URI' => "/hieraki/", 'SCRIPT_NAME' => "/hieraki/dispatch.cgi" + assert_equal "/hieraki/", request.request_uri + assert_equal "/", request.path ActionController::Base.relative_url_root = nil ActionController::Base.relative_url_root = "/collaboration/hieraki" - @request.set_REQUEST_URI "/collaboration/hieraki/books/edit/2" - @request.env['SCRIPT_NAME'] = "/collaboration/hieraki/dispatch.cgi" - assert_equal "/collaboration/hieraki/books/edit/2", @request.request_uri - assert_equal "/books/edit/2", @request.path + request = stub_request 'REQUEST_URI' => "/collaboration/hieraki/books/edit/2", + 'SCRIPT_NAME' => "/collaboration/hieraki/dispatch.cgi" + assert_equal "/collaboration/hieraki/books/edit/2", request.request_uri + assert_equal "/books/edit/2", request.path ActionController::Base.relative_url_root = nil # The following tests are for when REQUEST_URI is not supplied (as in IIS) - @request.env['PATH_INFO'] = "/path/of/some/uri?mapped=1" - @request.env['SCRIPT_NAME'] = nil #"/path/dispatch.rb" - @request.set_REQUEST_URI nil - assert_equal "/path/of/some/uri?mapped=1", @request.request_uri - assert_equal "/path/of/some/uri", @request.path + request = stub_request 'PATH_INFO' => "/path/of/some/uri?mapped=1", + 'SCRIPT_NAME' => nil, + 'REQUEST_URI' => nil + assert_equal "/path/of/some/uri?mapped=1", request.request_uri + assert_equal "/path/of/some/uri", request.path ActionController::Base.relative_url_root = '/path' - @request.env['PATH_INFO'] = "/path/of/some/uri?mapped=1" - @request.env['SCRIPT_NAME'] = "/path/dispatch.rb" - @request.set_REQUEST_URI nil - assert_equal "/path/of/some/uri?mapped=1", @request.request_uri - assert_equal "/of/some/uri", @request.path + request = stub_request 'PATH_INFO' => "/path/of/some/uri?mapped=1", + 'SCRIPT_NAME' => "/path/dispatch.rb", + 'REQUEST_URI' => nil + assert_equal "/path/of/some/uri?mapped=1", request.request_uri + assert_equal "/of/some/uri", request.path ActionController::Base.relative_url_root = nil - @request.env['PATH_INFO'] = "/path/of/some/uri" - @request.env['SCRIPT_NAME'] = nil - @request.set_REQUEST_URI nil - assert_equal "/path/of/some/uri", @request.request_uri - assert_equal "/path/of/some/uri", @request.path + request = stub_request 'PATH_INFO' => "/path/of/some/uri", + 'SCRIPT_NAME' => nil, + 'REQUEST_URI' => nil + assert_equal "/path/of/some/uri", request.request_uri + assert_equal "/path/of/some/uri", request.path - @request.env['PATH_INFO'] = "/" - @request.set_REQUEST_URI nil - assert_equal "/", @request.request_uri - assert_equal "/", @request.path + request = stub_request 'PATH_INFO' => '/', 'REQUEST_URI' => nil + assert_equal "/", request.request_uri + assert_equal "/", request.path - @request.env['PATH_INFO'] = "/?m=b" - @request.set_REQUEST_URI nil - assert_equal "/?m=b", @request.request_uri - assert_equal "/", @request.path + request = stub_request 'PATH_INFO' => '/?m=b', 'REQUEST_URI' => nil + assert_equal "/?m=b", request.request_uri + assert_equal "/", request.path - @request.env['PATH_INFO'] = "/" - @request.env['SCRIPT_NAME'] = "/dispatch.cgi" - @request.set_REQUEST_URI nil - assert_equal "/", @request.request_uri - assert_equal "/", @request.path + request = stub_request 'PATH_INFO' => "/", + 'SCRIPT_NAME' => "/dispatch.cgi", + 'REQUEST_URI' => nil + assert_equal "/", request.request_uri + assert_equal "/", request.path ActionController::Base.relative_url_root = '/hieraki' - @request.env['PATH_INFO'] = "/hieraki/" - @request.env['SCRIPT_NAME'] = "/hieraki/dispatch.cgi" - @request.set_REQUEST_URI nil - assert_equal "/hieraki/", @request.request_uri - assert_equal "/", @request.path + request = stub_request 'PATH_INFO' => "/hieraki/", + 'SCRIPT_NAME' => "/hieraki/dispatch.cgi", + 'REQUEST_URI' => nil + assert_equal "/hieraki/", request.request_uri + assert_equal "/", request.path ActionController::Base.relative_url_root = nil - @request.set_REQUEST_URI '/hieraki/dispatch.cgi' + request = stub_request 'REQUEST_URI' => '/hieraki/dispatch.cgi' ActionController::Base.relative_url_root = '/hieraki' - assert_equal "/dispatch.cgi", @request.path + assert_equal "/dispatch.cgi", request.path ActionController::Base.relative_url_root = nil - @request.set_REQUEST_URI '/hieraki/dispatch.cgi' + request = stub_request 'REQUEST_URI' => '/hieraki/dispatch.cgi' ActionController::Base.relative_url_root = '/foo' - assert_equal "/hieraki/dispatch.cgi", @request.path + assert_equal "/hieraki/dispatch.cgi", request.path ActionController::Base.relative_url_root = nil # This test ensures that Rails uses REQUEST_URI over PATH_INFO ActionController::Base.relative_url_root = nil - @request.env['REQUEST_URI'] = "/some/path" - @request.env['PATH_INFO'] = "/another/path" - @request.env['SCRIPT_NAME'] = "/dispatch.cgi" - assert_equal "/some/path", @request.request_uri - assert_equal "/some/path", @request.path + request = stub_request 'REQUEST_URI' => "/some/path", + 'PATH_INFO' => "/another/path", + 'SCRIPT_NAME' => "/dispatch.cgi" + assert_equal "/some/path", request.request_uri + assert_equal "/some/path", request.path end + test "host with default port" do - @request.host = "rubyonrails.org" - @request.port = 80 - assert_equal "rubyonrails.org", @request.host_with_port + request = stub_request 'HTTP_HOST' => 'rubyonrails.org:80' + assert_equal "rubyonrails.org", request.host_with_port end test "host with non default port" do - @request.host = "rubyonrails.org" - @request.port = 81 - assert_equal "rubyonrails.org:81", @request.host_with_port + request = stub_request 'HTTP_HOST' => 'rubyonrails.org:81' + assert_equal "rubyonrails.org:81", request.host_with_port end test "server software" do - assert_equal nil, @request.server_software + request = stub_request + assert_equal nil, request.server_software - @request.env['SERVER_SOFTWARE'] = 'Apache3.422' - assert_equal 'apache', @request.server_software + request = stub_request 'SERVER_SOFTWARE' => 'Apache3.422' + assert_equal 'apache', request.server_software - @request.env['SERVER_SOFTWARE'] = 'lighttpd(1.1.4)' - assert_equal 'lighttpd', @request.server_software + request = stub_request 'SERVER_SOFTWARE' => 'lighttpd(1.1.4)' + assert_equal 'lighttpd', request.server_software end test "xml http request" do - assert !@request.xml_http_request? - assert !@request.xhr? + request = stub_request + + assert !request.xml_http_request? + assert !request.xhr? - @request.env['HTTP_X_REQUESTED_WITH'] = "DefinitelyNotAjax1.0" - assert !@request.xml_http_request? - assert !@request.xhr? + request = stub_request 'HTTP_X_REQUESTED_WITH' => 'DefinitelyNotAjax1.0' + assert !request.xml_http_request? + assert !request.xhr? - @request.env['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest" - assert @request.xml_http_request? - assert @request.xhr? + request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' + assert request.xml_http_request? + assert request.xhr? end test "reports ssl" do - assert !@request.ssl? - @request.env['HTTPS'] = 'on' - assert @request.ssl? + request = stub_request + assert !request.ssl? + + request = stub_request 'HTTPS' => 'on' + assert request.ssl? end test "reports ssl when proxied via lighttpd" do - assert !@request.ssl? - @request.env['HTTP_X_FORWARDED_PROTO'] = 'https' - assert @request.ssl? + request = stub_request + assert !request.ssl? + + request = stub_request 'HTTP_X_FORWARDED_PROTO' => 'https' + assert request.ssl? end test "symbolized request methods" do [:get, :post, :put, :delete].each do |method| - self.request_method = method - assert_equal method, @request.method + request = stub_request 'REQUEST_METHOD' => method.to_s.upcase + assert_equal method, request.method end end test "invalid http method raises exception" do - assert_raises(ActionController::UnknownHttpMethod) do - self.request_method = :random_method - @request.request_method + assert_raise(ActionController::UnknownHttpMethod) do + request = stub_request 'REQUEST_METHOD' => 'RANDOM_METHOD' + request.request_method end end test "allow method hacking on post" do [:get, :head, :options, :put, :post, :delete].each do |method| - self.request_method = method - assert_equal(method == :head ? :get : method, @request.method) + request = stub_request "REQUEST_METHOD" => method.to_s.upcase + assert_equal(method == :head ? :get : method, request.method) end end test "invalid method hacking on post raises exception" do - assert_raises(ActionController::UnknownHttpMethod) do - self.request_method = :_random_method - @request.request_method + assert_raise(ActionController::UnknownHttpMethod) do + request = stub_request "REQUEST_METHOD" => "_RANDOM_METHOD" + request.request_method end end test "restrict method hacking" do - @request.instance_eval { @parameters = { :_method => 'put' } } [:get, :put, :delete].each do |method| - self.request_method = method - assert_equal method, @request.method + request = stub_request 'REQUEST_METHOD' => method.to_s.upcase, + 'action_controller.request.request_parameters' => { :_method => 'put' } + assert_equal method, request.method end end test "head masquerading as get" do - self.request_method = :head - assert_equal :get, @request.method - assert @request.get? - assert @request.head? + request = stub_request 'REQUEST_METHOD' => 'HEAD' + assert_equal :get, request.method + assert request.get? + assert request.head? end test "xml format" do - @request.instance_eval { @parameters = { :format => 'xml' } } - assert_equal Mime::XML, @request.format + request = stub_request + request.expects(:parameters).at_least_once.returns({ :format => 'xml' }) + assert_equal Mime::XML, request.format end test "xhtml format" do - @request.instance_eval { @parameters = { :format => 'xhtml' } } - assert_equal Mime::HTML, @request.format + request = stub_request + request.expects(:parameters).at_least_once.returns({ :format => 'xhtml' }) + assert_equal Mime::HTML, request.format end test "txt format" do - @request.instance_eval { @parameters = { :format => 'txt' } } - assert_equal Mime::TEXT, @request.format + request = stub_request + request.expects(:parameters).at_least_once.returns({ :format => 'txt' }) + assert_equal Mime::TEXT, request.format end - test "nil format" do + test "XMLHttpRequest" do begin ActionController::Base.use_accept_header, old = false, ActionController::Base.use_accept_header - @request.instance_eval { @parameters = {} } - @request.env["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" - assert @request.xhr? - assert_equal Mime::JS, @request.format - + request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' + request.expects(:parameters).at_least_once.returns({}) + assert request.xhr? + assert_equal Mime::JS, request.format ensure ActionController::Base.use_accept_header = old end end test "content type" do - @request.env["CONTENT_TYPE"] = "text/html" - assert_equal Mime::HTML, @request.content_type + request = stub_request 'CONTENT_TYPE' => 'text/html' + assert_equal Mime::HTML, request.content_type end - test "format assignment should set format" do - @request.instance_eval { self.format = :txt } - assert !@request.format.xml? - @request.instance_eval { self.format = :xml } - assert @request.format.xml? + test "can override format with parameter" do + request = stub_request + request.expects(:parameters).at_least_once.returns({ :format => :txt }) + assert !request.format.xml? + + request = stub_request + request.expects(:parameters).at_least_once.returns({ :format => :xml }) + assert request.format.xml? end - test "content no type" do - assert_equal nil, @request.content_type + test "no content type" do + request = stub_request + assert_equal nil, request.content_type end - test "content type xml" do - @request.env["CONTENT_TYPE"] = "application/xml" - assert_equal Mime::XML, @request.content_type + test "content type is XML" do + request = stub_request 'CONTENT_TYPE' => 'application/xml' + assert_equal Mime::XML, request.content_type end test "content type with charset" do - @request.env["CONTENT_TYPE"] = "application/xml; charset=UTF-8" - assert_equal Mime::XML, @request.content_type + request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8' + assert_equal Mime::XML, request.content_type end test "user agent" do - assert_not_nil @request.user_agent + request = stub_request 'HTTP_USER_AGENT' => 'TestAgent' + assert_equal 'TestAgent', request.user_agent end test "parameters" do - @request.stubs(:request_parameters).returns({ "foo" => 1 }) - @request.stubs(:query_parameters).returns({ "bar" => 2 }) + request = stub_request + request.stubs(:request_parameters).returns({ "foo" => 1 }) + request.stubs(:query_parameters).returns({ "bar" => 2 }) - assert_equal({"foo" => 1, "bar" => 2}, @request.parameters) - assert_equal({"foo" => 1}, @request.request_parameters) - assert_equal({"bar" => 2}, @request.query_parameters) + assert_equal({"foo" => 1, "bar" => 2}, request.parameters) + assert_equal({"foo" => 1}, request.request_parameters) + assert_equal({"bar" => 2}, request.query_parameters) + end + +protected + + def stub_request(env={}) + ActionDispatch::Request.new(env) end - protected - def request_method=(method) - @request.env['REQUEST_METHOD'] = method.to_s.upcase - @request.request_method = nil # Reset the ivar cache - end end diff --git a/actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml b/actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml 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/public/500.da.html b/actionpack/test/fixtures/public/500.da.html new file mode 100644 index 0000000000..a497c13656 --- /dev/null +++ b/actionpack/test/fixtures/public/500.da.html @@ -0,0 +1 @@ +500 localized error fixture 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/hello_world.erb~ b/actionpack/test/fixtures/test/hello_world.erb~ new file mode 100644 index 0000000000..21934a1c95 --- /dev/null +++ b/actionpack/test/fixtures/test/hello_world.erb~ @@ -0,0 +1 @@ +Don't pick me!
\ No newline at end of file diff --git a/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb b/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb new file mode 100644 index 0000000000..773b3c8c6e --- /dev/null +++ b/actionpack/test/fixtures/test/hello_world.pt-BR.html.erb @@ -0,0 +1 @@ +Ola mundo
\ 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/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb b/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb new file mode 100644 index 0000000000..0740b2d07c --- /dev/null +++ b/actionpack/test/fixtures/test/render_implicit_html_template_from_xhr_request.da.html.erb @@ -0,0 +1 @@ +Hey HTML! diff --git a/actionpack/test/fixtures/test/utf8.html.erb b/actionpack/test/fixtures/test/utf8.html.erb new file mode 100644 index 0000000000..0b4d19aa0e --- /dev/null +++ b/actionpack/test/fixtures/test/utf8.html.erb @@ -0,0 +1,2 @@ +Русский текст +日本語のテキスト
\ No newline at end of file diff --git a/actionpack/test/template/active_record_helper_i18n_test.rb b/actionpack/test/template/active_record_helper_i18n_test.rb index 7e6bf70706..9d04c882c8 100644 --- a/actionpack/test/template/active_record_helper_i18n_test.rb +++ b/actionpack/test/template/active_record_helper_i18n_test.rb @@ -4,43 +4,44 @@ class ActiveRecordHelperI18nTest < Test::Unit::TestCase include ActionView::Helpers::ActiveRecordHelper attr_reader :request - uses_mocha 'active_record_helper_i18n_test' do - def setup - @object = stub :errors => stub(:count => 1, :full_messages => ['full_messages']) - @object_name = 'book' - stubs(:content_tag).returns 'content_tag' - - I18n.stubs(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved" - I18n.stubs(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:' - end - - def test_error_messages_for_given_a_header_option_it_does_not_translate_header_message - I18n.expects(:translate).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never - error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en') - end - - def test_error_messages_for_given_no_header_option_it_translates_header_message - I18n.expects(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message' - I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns '' - error_messages_for(:object => @object, :locale => 'en') - end - - def test_error_messages_for_given_a_message_option_it_does_not_translate_message - I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).never - I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns '' - error_messages_for(:object => @object, :message => 'message', :locale => 'en') - end - - def test_error_messages_for_given_no_message_option_it_translates_message - I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:' - I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns '' - error_messages_for(:object => @object, :locale => 'en') - end - - def test_error_messages_for_given_object_name_it_translates_object_name - I18n.expects(:t).with(:header, :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name).returns "1 error prohibited this #{@object_name} from being saved" - I18n.expects(:t).with(@object_name, :default => @object_name, :count => 1, :scope => [:activerecord, :models]).once.returns @object_name - error_messages_for(:object => @object, :locale => 'en', :object_name => @object_name) - end + + def setup + @object = stub :errors => stub(:count => 1, :full_messages => ['full_messages']) + @object_name = 'book_seller' + @object_name_without_underscore = 'book seller' + + stubs(:content_tag).returns 'content_tag' + + I18n.stubs(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns "1 error prohibited this from being saved" + I18n.stubs(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:' + end + + def test_error_messages_for_given_a_header_option_it_does_not_translate_header_message + I18n.expects(:translate).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').never + error_messages_for(:object => @object, :header_message => 'header message', :locale => 'en') + end + + def test_error_messages_for_given_no_header_option_it_translates_header_message + I18n.expects(:t).with(:'header', :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => '').returns 'header message' + I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns '' + error_messages_for(:object => @object, :locale => 'en') + end + + def test_error_messages_for_given_a_message_option_it_does_not_translate_message + I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).never + I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns '' + error_messages_for(:object => @object, :message => 'message', :locale => 'en') + end + + def test_error_messages_for_given_no_message_option_it_translates_message + I18n.expects(:t).with(:'body', :locale => 'en', :scope => [:activerecord, :errors, :template]).returns 'There were problems with the following fields:' + I18n.expects(:t).with('', :default => '', :count => 1, :scope => [:activerecord, :models]).once.returns '' + error_messages_for(:object => @object, :locale => 'en') + end + + def test_error_messages_for_given_object_name_it_translates_object_name + I18n.expects(:t).with(:header, :locale => 'en', :scope => [:activerecord, :errors, :template], :count => 1, :model => @object_name_without_underscore).returns "1 error prohibited this #{@object_name_without_underscore} from being saved" + I18n.expects(:t).with(@object_name, :default => @object_name_without_underscore, :count => 1, :scope => [:activerecord, :models]).once.returns @object_name_without_underscore + error_messages_for(:object => @object, :locale => 'en', :object_name => @object_name) end end diff --git a/actionpack/test/template/active_record_helper_test.rb b/actionpack/test/template/active_record_helper_test.rb index f03998231e..b4b8cbe074 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 @@ -196,10 +220,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/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index 44eca55a0e..76ceff8d6c 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -229,20 +229,18 @@ class AssetTagHelperTest < ActionView::TestCase ImageLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end - uses_mocha 'test image tag with windows behaviour' do - def test_image_tag_windows_behaviour - old_asset_id, ENV["RAILS_ASSET_ID"] = ENV["RAILS_ASSET_ID"], "1" - # This simulates the behaviour of File#exist? on windows when testing a file ending in "." - # If the file "rails.png" exists, windows will return true when asked if "rails.png." exists (notice trailing ".") - # OS X, linux etc will return false in this case. - File.stubs(:exist?).with('template/../fixtures/public/images/rails.png.').returns(true) - assert_equal '<img alt="Rails" src="/images/rails.png?1" />', image_tag('rails.png') - ensure - if old_asset_id - ENV["RAILS_ASSET_ID"] = old_asset_id - else - ENV.delete("RAILS_ASSET_ID") - end + def test_image_tag_windows_behaviour + old_asset_id, ENV["RAILS_ASSET_ID"] = ENV["RAILS_ASSET_ID"], "1" + # This simulates the behaviour of File#exist? on windows when testing a file ending in "." + # If the file "rails.png" exists, windows will return true when asked if "rails.png." exists (notice trailing ".") + # OS X, linux etc will return false in this case. + File.stubs(:exist?).with('template/../fixtures/public/images/rails.png.').returns(true) + assert_equal '<img alt="Rails" src="/images/rails.png?1" />', image_tag('rails.png') + ensure + if old_asset_id + ENV["RAILS_ASSET_ID"] = old_asset_id + else + ENV.delete("RAILS_ASSET_ID") end end diff --git a/actionpack/test/template/body_parts_test.rb b/actionpack/test/template/body_parts_test.rb new file mode 100644 index 0000000000..4c82b75cdc --- /dev/null +++ b/actionpack/test/template/body_parts_test.rb @@ -0,0 +1,22 @@ +require 'abstract_unit' + +class BodyPartsTest < ActionController::TestCase + RENDERINGS = [Object.new, Object.new, Object.new] + + class TestController < ActionController::Base + def index + RENDERINGS.each do |rendering| + response.template.punctuate_body! rendering + end + @performed_render = true + end + end + + tests TestController + + def test_body_parts + get :index + assert_equal RENDERINGS, @response.body_parts + assert_equal RENDERINGS.join, @response.body + end +end diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb index caea1bd643..a7ed13cf57 100644 --- a/actionpack/test/template/compiled_templates_test.rb +++ b/actionpack/test/template/compiled_templates_test.rb @@ -1,87 +1,85 @@ require 'abstract_unit' require 'controller/fake_models' -uses_mocha 'TestTemplateRecompilation' do - class CompiledTemplatesTest < Test::Unit::TestCase - def setup - @compiled_templates = ActionView::Base::CompiledTemplates - @compiled_templates.instance_methods.each do |m| - @compiled_templates.send(:remove_method, m) if m =~ /^_run_/ - end +class CompiledTemplatesTest < Test::Unit::TestCase + def setup + @compiled_templates = ActionView::Base::CompiledTemplates + @compiled_templates.instance_methods.each do |m| + @compiled_templates.send(:remove_method, m) if m =~ /^_run_/ end + end - def test_template_gets_compiled - assert_equal 0, @compiled_templates.instance_methods.size - assert_equal "Hello world!", render(:file => "test/hello_world.erb") - assert_equal 1, @compiled_templates.instance_methods.size - end + def test_template_gets_compiled + assert_equal 0, @compiled_templates.instance_methods.size + assert_equal "Hello world!", render(:file => "test/hello_world.erb") + assert_equal 1, @compiled_templates.instance_methods.size + end - def test_template_gets_recompiled_when_using_different_keys_in_local_assigns - assert_equal 0, @compiled_templates.instance_methods.size - assert_equal "Hello world!", render(:file => "test/hello_world.erb") - assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"}) - assert_equal 2, @compiled_templates.instance_methods.size - end + def test_template_gets_recompiled_when_using_different_keys_in_local_assigns + assert_equal 0, @compiled_templates.instance_methods.size + assert_equal "Hello world!", render(:file => "test/hello_world.erb") + assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"}) + assert_equal 2, @compiled_templates.instance_methods.size + end - def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns - assert_equal 0, @compiled_templates.instance_methods.size - assert_equal "Hello world!", render(:file => "test/hello_world.erb") - ActionView::Template.any_instance.expects(:compile!).never - assert_equal "Hello world!", render(:file => "test/hello_world.erb") - end + def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns + assert_equal 0, @compiled_templates.instance_methods.size + assert_equal "Hello world!", render(:file => "test/hello_world.erb") + ActionView::Template.any_instance.expects(:compile!).never + assert_equal "Hello world!", render(:file => "test/hello_world.erb") + end - def test_compiled_template_will_always_be_recompiled_when_template_is_not_cached - ActionView::Template.any_instance.expects(:recompile?).times(3).returns(true) - assert_equal 0, @compiled_templates.instance_methods.size - assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") - ActionView::Template.any_instance.expects(:compile!).times(3) - 3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") } - assert_equal 1, @compiled_templates.instance_methods.size - end + def test_compiled_template_will_always_be_recompiled_when_template_is_not_cached + ActionView::Template.any_instance.expects(:recompile?).times(3).returns(true) + assert_equal 0, @compiled_templates.instance_methods.size + assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") + ActionView::Template.any_instance.expects(:compile!).times(3) + 3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") } + assert_equal 1, @compiled_templates.instance_methods.size + end - def test_template_changes_are_not_reflected_with_cached_templates - assert_equal "Hello world!", render(:file => "test/hello_world.erb") - modify_template "test/hello_world.erb", "Goodbye world!" do - assert_equal "Hello world!", render(:file => "test/hello_world.erb") - end + def test_template_changes_are_not_reflected_with_cached_templates + assert_equal "Hello world!", render(:file => "test/hello_world.erb") + modify_template "test/hello_world.erb", "Goodbye world!" do assert_equal "Hello world!", render(:file => "test/hello_world.erb") end + assert_equal "Hello world!", render(:file => "test/hello_world.erb") + end - def test_template_changes_are_reflected_with_uncached_templates - assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb") - modify_template "test/hello_world.erb", "Goodbye world!" do - assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb") - end - assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb") + def test_template_changes_are_reflected_with_uncached_templates + assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb") + modify_template "test/hello_world.erb", "Goodbye world!" do + assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb") end + assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb") + end - private - def render(*args) - render_with_cache(*args) - end + private + def render(*args) + render_with_cache(*args) + end - def render_with_cache(*args) - view_paths = ActionController::Base.view_paths - assert_equal ActionView::Template::EagerPath, view_paths.first.class - ActionView::Base.new(view_paths, {}).render(*args) - end + def render_with_cache(*args) + view_paths = ActionController::Base.view_paths + assert_equal ActionView::Template::EagerPath, view_paths.first.class + ActionView::Base.new(view_paths, {}).render(*args) + end - def render_without_cache(*args) - path = ActionView::Template::Path.new(FIXTURE_LOAD_PATH) - view_paths = ActionView::Base.process_view_paths(path) - assert_equal ActionView::Template::Path, view_paths.first.class - ActionView::Base.new(view_paths, {}).render(*args) - end + def render_without_cache(*args) + path = ActionView::Template::Path.new(FIXTURE_LOAD_PATH) + view_paths = ActionView::Base.process_view_paths(path) + assert_equal ActionView::Template::Path, view_paths.first.class + ActionView::Base.new(view_paths, {}).render(*args) + end - def modify_template(template, content) - filename = "#{FIXTURE_LOAD_PATH}/#{template}" - old_content = File.read(filename) - begin - File.open(filename, "wb+") { |f| f.write(content) } - yield - ensure - File.open(filename, "wb+") { |f| f.write(old_content) } - end + def modify_template(template, content) + filename = "#{FIXTURE_LOAD_PATH}/#{template}" + old_content = File.read(filename) + begin + File.open(filename, "wb+") { |f| f.write(content) } + yield + ensure + File.open(filename, "wb+") { |f| f.write(old_content) } end - end + end end diff --git a/actionpack/test/template/date_helper_i18n_test.rb b/actionpack/test/template/date_helper_i18n_test.rb index fac30da128..bc011f59b8 100644 --- a/actionpack/test/template/date_helper_i18n_test.rb +++ b/actionpack/test/template/date_helper_i18n_test.rb @@ -8,66 +8,64 @@ class DateHelperDistanceOfTimeInWordsI18nTests < Test::Unit::TestCase @from = Time.mktime(2004, 6, 6, 21, 45, 0) end - uses_mocha 'date_helper_distance_of_time_in_words_i18n_test' do - # distance_of_time_in_words - - def test_distance_of_time_in_words_calls_i18n - { # with include_seconds - [2.seconds, true] => [:'less_than_x_seconds', 5], - [9.seconds, true] => [:'less_than_x_seconds', 10], - [19.seconds, true] => [:'less_than_x_seconds', 20], - [30.seconds, true] => [:'half_a_minute', nil], - [59.seconds, true] => [:'less_than_x_minutes', 1], - [60.seconds, true] => [:'x_minutes', 1], - - # without include_seconds - [29.seconds, false] => [:'less_than_x_minutes', 1], - [60.seconds, false] => [:'x_minutes', 1], - [44.minutes, false] => [:'x_minutes', 44], - [61.minutes, false] => [:'about_x_hours', 1], - [24.hours, false] => [:'x_days', 1], - [30.days, false] => [:'about_x_months', 1], - [60.days, false] => [:'x_months', 2], - [1.year, false] => [:'about_x_years', 1], - [3.years, false] => [:'over_x_years', 3] - - }.each do |passed, expected| - assert_distance_of_time_in_words_translates_key passed, expected - end + # distance_of_time_in_words + + def test_distance_of_time_in_words_calls_i18n + { # with include_seconds + [2.seconds, true] => [:'less_than_x_seconds', 5], + [9.seconds, true] => [:'less_than_x_seconds', 10], + [19.seconds, true] => [:'less_than_x_seconds', 20], + [30.seconds, true] => [:'half_a_minute', nil], + [59.seconds, true] => [:'less_than_x_minutes', 1], + [60.seconds, true] => [:'x_minutes', 1], + + # without include_seconds + [29.seconds, false] => [:'less_than_x_minutes', 1], + [60.seconds, false] => [:'x_minutes', 1], + [44.minutes, false] => [:'x_minutes', 44], + [61.minutes, false] => [:'about_x_hours', 1], + [24.hours, false] => [:'x_days', 1], + [30.days, false] => [:'about_x_months', 1], + [60.days, false] => [:'x_months', 2], + [1.year, false] => [:'about_x_years', 1], + [3.years, false] => [:'over_x_years', 3] + + }.each do |passed, expected| + assert_distance_of_time_in_words_translates_key passed, expected end + end - def assert_distance_of_time_in_words_translates_key(passed, expected) - diff, include_seconds = *passed - key, count = *expected - to = @from + diff + def assert_distance_of_time_in_words_translates_key(passed, expected) + diff, include_seconds = *passed + key, count = *expected + to = @from + diff - options = {:locale => 'en', :scope => :'datetime.distance_in_words'} - options[:count] = count if count + options = {:locale => 'en', :scope => :'datetime.distance_in_words'} + options[:count] = count if count - I18n.expects(:t).with(key, options) - distance_of_time_in_words(@from, to, include_seconds, :locale => 'en') - end + I18n.expects(:t).with(key, options) + distance_of_time_in_words(@from, to, include_seconds, :locale => 'en') + end - def test_distance_of_time_pluralizations - { [:'less_than_x_seconds', 1] => 'less than 1 second', - [:'less_than_x_seconds', 2] => 'less than 2 seconds', - [:'less_than_x_minutes', 1] => 'less than a minute', - [:'less_than_x_minutes', 2] => 'less than 2 minutes', - [:'x_minutes', 1] => '1 minute', - [:'x_minutes', 2] => '2 minutes', - [:'about_x_hours', 1] => 'about 1 hour', - [:'about_x_hours', 2] => 'about 2 hours', - [:'x_days', 1] => '1 day', - [:'x_days', 2] => '2 days', - [:'about_x_years', 1] => 'about 1 year', - [:'about_x_years', 2] => 'about 2 years', - [:'over_x_years', 1] => 'over 1 year', - [:'over_x_years', 2] => 'over 2 years' - - }.each do |args, expected| - key, count = *args - assert_equal expected, I18n.t(key, :count => count, :scope => 'datetime.distance_in_words') - end + def test_distance_of_time_pluralizations + { [:'less_than_x_seconds', 1] => 'less than 1 second', + [:'less_than_x_seconds', 2] => 'less than 2 seconds', + [:'less_than_x_minutes', 1] => 'less than a minute', + [:'less_than_x_minutes', 2] => 'less than 2 minutes', + [:'x_minutes', 1] => '1 minute', + [:'x_minutes', 2] => '2 minutes', + [:'about_x_hours', 1] => 'about 1 hour', + [:'about_x_hours', 2] => 'about 2 hours', + [:'x_days', 1] => '1 day', + [:'x_days', 2] => '2 days', + [:'about_x_years', 1] => 'about 1 year', + [:'about_x_years', 2] => 'about 2 years', + [:'over_x_years', 1] => 'over 1 year', + [:'over_x_years', 2] => 'over 2 years' + + }.each do |args, expected| + key, count = *args + assert_equal expected, I18n.t(key, :count => count, :scope => 'datetime.distance_in_words') end end end @@ -76,49 +74,47 @@ class DateHelperSelectTagsI18nTests < Test::Unit::TestCase include ActionView::Helpers::DateHelper attr_reader :request - uses_mocha 'date_helper_select_tags_i18n_tests' do - def setup - @prompt_defaults = {:year => 'Year', :month => 'Month', :day => 'Day', :hour => 'Hour', :minute => 'Minute', :second => 'Seconds'} - - I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES - end + def setup + @prompt_defaults = {:year => 'Year', :month => 'Month', :day => 'Day', :hour => 'Hour', :minute => 'Minute', :second => 'Seconds'} - # select_month + I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES + end - def test_select_month_given_use_month_names_option_does_not_translate_monthnames - I18n.expects(:translate).never - select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES) - end + # select_month - def test_select_month_translates_monthnames - I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES - select_month(8, :locale => 'en') - end + def test_select_month_given_use_month_names_option_does_not_translate_monthnames + I18n.expects(:translate).never + select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES) + end - def test_select_month_given_use_short_month_option_translates_abbr_monthnames - I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES - select_month(8, :locale => 'en', :use_short_month => true) - end + def test_select_month_translates_monthnames + I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES + select_month(8, :locale => 'en') + end - def test_date_or_time_select_translates_prompts - @prompt_defaults.each do |key, prompt| - I18n.expects(:translate).with(('datetime.prompts.' + key.to_s).to_sym, :locale => 'en').returns prompt - end + def test_select_month_given_use_short_month_option_translates_abbr_monthnames + I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES + select_month(8, :locale => 'en', :use_short_month => true) + end - I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day] - datetime_select('post', 'updated_at', :locale => 'en', :include_seconds => true, :prompt => true) + def test_date_or_time_select_translates_prompts + @prompt_defaults.each do |key, prompt| + I18n.expects(:translate).with(('datetime.prompts.' + key.to_s).to_sym, :locale => 'en').returns prompt end - # date_or_time_select + I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day] + datetime_select('post', 'updated_at', :locale => 'en', :include_seconds => true, :prompt => true) + end - def test_date_or_time_select_given_an_order_options_does_not_translate_order - I18n.expects(:translate).never - datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en') - end + # date_or_time_select - def test_date_or_time_select_given_no_order_options_translates_order - I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day] - datetime_select('post', 'updated_at', :locale => 'en') - end + def test_date_or_time_select_given_an_order_options_does_not_translate_order + I18n.expects(:translate).never + datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en') + end + + def test_date_or_time_select_given_no_order_options_translates_order + I18n.expects(:translate).with(:'date.order', :locale => 'en').returns [:year, :month, :day] + datetime_select('post', 'updated_at', :locale => 'en') end -end
\ No newline at end of file +end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index 92cdce2e45..2e4763f446 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -1726,40 +1726,38 @@ class DateHelperTest < ActionView::TestCase assert_dom_equal expected, datetime_select("post", "updated_at") end - uses_mocha 'TestDatetimeSelectDefaultsToTimeZoneNowWhenConfigTimeZoneIsSet' do - def test_datetime_select_defaults_to_time_zone_now_when_config_time_zone_is_set - time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0) - time_zone = mock() - time_zone.expects(:now).returns time - Time.zone_default = time_zone - @post = Post.new - - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} - expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} - expected << "</select>\n" - - expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} - expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} - expected << "</select>\n" - - expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n} - expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} - expected << "</select>\n" - - expected << " — " - - expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n} - expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n} - expected << "</select>\n" - expected << " : " - expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n} - expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35" selected="selected">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n} - expected << "</select>\n" - - assert_dom_equal expected, datetime_select("post", "updated_at") - ensure - Time.zone_default = nil - end + def test_datetime_select_defaults_to_time_zone_now_when_config_time_zone_is_set + time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0) + time_zone = mock() + time_zone.expects(:now).returns time + Time.zone_default = time_zone + @post = Post.new + + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} + expected << "</select>\n" + + expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} + expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} + expected << "</select>\n" + + expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n} + expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} + expected << "</select>\n" + + expected << " — " + + expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n} + expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n} + expected << "</select>\n" + expected << " : " + expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n} + expected << %{<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35" selected="selected">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n} + expected << "</select>\n" + + assert_dom_equal expected, datetime_select("post", "updated_at") + ensure + Time.zone_default = nil end def test_datetime_select_with_html_options_within_fields_for @@ -1822,60 +1820,60 @@ class DateHelperTest < ActionView::TestCase def test_datetime_select_with_default_prompt @post = Post.new - @post.updated_at = Time.local(2004, 6, 15, 16, 35) + @post.updated_at = nil expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} - expected << %{<option value="">Year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} + expected << %{<option value="">Year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} - expected << %{<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} + expected << %{<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} expected << "</select>\n" expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n} - expected << %{<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} + expected << %{<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} expected << "</select>\n" expected << " — " expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n} - expected << %{<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n} + expected << %{<option value="">Hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n} expected << "</select>\n" expected << " : " expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n} - expected << %{<option value="">Minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35" selected="selected">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n} + expected << %{<option value="">Minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n} expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :prompt => true) + assert_dom_equal expected, datetime_select("post", "updated_at", :start_year=>1999, :end_year=>2009, :prompt => true) end def test_datetime_select_with_custom_prompt @post = Post.new - @post.updated_at = Time.local(2004, 6, 15, 16, 35) + @post.updated_at = nil expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} - expected << %{<option value="">Choose year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} + expected << %{<option value="">Choose year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} - expected << %{<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} + expected << %{<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} expected << "</select>\n" expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n} - expected << %{<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} + expected << %{<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} expected << "</select>\n" expected << " — " expected << %{<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n} - expected << %{<option value="">Choose hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n} + expected << %{<option value="">Choose hour</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n} expected << "</select>\n" expected << " : " expected << %{<select id="post_updated_at_5i" name="post[updated_at(5i)]">\n} - expected << %{<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35" selected="selected">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n} + expected << %{<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n} expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :prompt => {:year => 'Choose year', :month => 'Choose month', :day => 'Choose day', :hour => 'Choose hour', :minute => 'Choose minute'}) + assert_dom_equal expected, datetime_select("post", "updated_at", :start_year=>1999, :end_year=>2009, :prompt => {:year => 'Choose year', :month => 'Choose month', :day => 'Choose day', :hour => 'Choose hour', :minute => 'Choose minute'}) end def test_date_select_with_zero_value_and_no_start_year diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index e268728c79..104649deac 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -15,21 +15,31 @@ silence_warnings do def new_record? @new_record end + + attr_accessor :author + def author_attributes=(attributes); end + + attr_accessor :comments + def comments_attributes=(attributes); end end class Comment attr_reader :id attr_reader :post_id + def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end def save; @id = 1; @post_id = 1 end def new_record?; @id.nil? end def to_param; @id; end def name - @id.nil? ? 'new comment' : "comment ##{@id}" + @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" end end -end -class Comment::Nested < Comment; end + class Author < Comment + attr_accessor :post + def post_attributes=(attributes); end + end +end class FormHelperTest < ActionView::TestCase tests ActionView::Helpers::FormHelper @@ -161,36 +171,36 @@ class FormHelperTest < ActionView::TestCase def test_check_box assert_dom_equal( - '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret") ) @post.secret = 0 assert_dom_equal( - '<input id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret") ) assert_dom_equal( - '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret" ,{"checked"=>"checked"}) ) @post.secret = true assert_dom_equal( - '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret") ) assert_dom_equal( - '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret?") ) @post.secret = ['0'] assert_dom_equal( - '<input id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret") ) @post.secret = ['1'] assert_dom_equal( - '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret") ) end @@ -198,14 +208,14 @@ class FormHelperTest < ActionView::TestCase def test_check_box_with_explicit_checked_and_unchecked_values @post.secret = "on" assert_dom_equal( - '<input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="on" /><input name="post[secret]" type="hidden" value="off" />', + '<input name="post[secret]" type="hidden" value="off" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="on" />', check_box("post", "secret", {}, "on", "off") ) end def test_checkbox_disabled_still_submits_checked_value assert_dom_equal( - '<input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="1" />', + '<input name="post[secret]" type="hidden" value="1" /><input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret", { :disabled => :true }) ) end @@ -280,7 +290,7 @@ class FormHelperTest < ActionView::TestCase text_area("post", "body", "name" => "really!") ) assert_dom_equal( - '<input checked="checked" id="post_secret" name="i mean it" type="checkbox" value="1" /><input name="i mean it" type="hidden" value="0" />', + '<input name="i mean it" type="hidden" value="0" /><input checked="checked" id="post_secret" name="i mean it" type="checkbox" value="1" />', check_box("post", "secret", "name" => "i mean it") ) assert_dom_equal text_field("post", "title", "name" => "dont guess"), @@ -300,7 +310,7 @@ class FormHelperTest < ActionView::TestCase text_area("post", "body", "id" => "really!") ) assert_dom_equal( - '<input checked="checked" id="i mean it" name="post[secret]" type="checkbox" value="1" /><input name="post[secret]" type="hidden" value="0" />', + '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="i mean it" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret", "id" => "i mean it") ) assert_dom_equal text_field("post", "title", "id" => "dont guess"), @@ -325,7 +335,7 @@ class FormHelperTest < ActionView::TestCase text_area("post[]", "body") ) assert_dom_equal( - "<input checked=\"checked\" id=\"post_#{pid}_secret\" name=\"post[#{pid}][secret]\" type=\"checkbox\" value=\"1\" /><input name=\"post[#{pid}][secret]\" type=\"hidden\" value=\"0\" />", + "<input name=\"post[#{pid}][secret]\" type=\"hidden\" value=\"0\" /><input checked=\"checked\" id=\"post_#{pid}_secret\" name=\"post[#{pid}][secret]\" type=\"checkbox\" value=\"1\" />", check_box("post[]", "secret") ) assert_dom_equal( @@ -351,8 +361,8 @@ class FormHelperTest < ActionView::TestCase "<label for='post_title'>Title</label>" + "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + "<input name='post[secret]' type='hidden' value='0' />" + + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + "<input name='commit' id='post_submit' type='submit' value='Create post' />" + "</form>" @@ -371,8 +381,8 @@ class FormHelperTest < ActionView::TestCase "<div style='margin:0;padding:0'><input name='_method' type='hidden' value='put' /></div>" + "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + "<input name='post[secret]' type='hidden' value='0' />" + + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + "</form>" assert_dom_equal expected, output_buffer @@ -389,8 +399,8 @@ class FormHelperTest < ActionView::TestCase "<form action='http://www.example.com' id='create-post' method='post'>" + "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + "<input name='post[secret]' type='hidden' value='0' />" + + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + "</form>" assert_dom_equal expected, output_buffer @@ -409,8 +419,8 @@ class FormHelperTest < ActionView::TestCase "<label for=\"post_123_title\">Title</label>" + "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" + "<input name='post[123][secret]' type='hidden' value='0' />" + + "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" + "</form>" assert_dom_equal expected, output_buffer @@ -427,8 +437,8 @@ class FormHelperTest < ActionView::TestCase "<form action='http://www.example.com' method='post'>" + "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" + "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" + "<input name='post[][secret]' type='hidden' value='0' />" + + "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" + "</form>" assert_dom_equal expected, output_buffer @@ -480,7 +490,7 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end - def test_nested_fields_for_with_index + def test_form_for_with_index_and_nested_fields_for form_for(:post, @post, :index => 1) do |f| f.fields_for(:comment, @post) do |c| concat c.text_field(:title) @@ -559,6 +569,158 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_nested_fields_for_with_a_new_record_on_a_nested_attributes_one_to_one_association + @post.author = Author.new + + form_for(:post, @post) do |f| + concat f.text_field(:title) + f.fields_for(:author) do |af| + concat af.text_field(:name) + end + end + + expected = '<form action="http://www.example.com" method="post">' + + '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="new author" />' + + '</form>' + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_for_with_explicitly_passed_object_on_a_nested_attributes_one_to_one_association + form_for(:post, @post) do |f| + f.fields_for(:author, Author.new(123)) do |af| + assert_not_nil af.object + assert_equal 123, af.object.id + end + end + end + + def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association + @post.author = Author.new(321) + + form_for(:post, @post) do |f| + concat f.text_field(:title) + f.fields_for(:author) do |af| + concat af.text_field(:name) + end + end + + expected = '<form action="http://www.example.com" method="post">' + + '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + + '</form>' + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_for(:post, @post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + f.fields_for(:comments, comment) do |cf| + concat cf.text_field(:name) + end + end + end + + expected = '<form action="http://www.example.com" method="post">' + + '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + + '</form>' + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_for_with_new_records_on_a_nested_attributes_collection_association + @post.comments = [Comment.new, Comment.new] + + form_for(:post, @post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + f.fields_for(:comments, comment) do |cf| + concat cf.text_field(:name) + end + end + end + + expected = '<form action="http://www.example.com" method="post">' + + '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="new comment" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + + '</form>' + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_for_with_existing_and_new_records_on_a_nested_attributes_collection_association + @post.comments = [Comment.new(321), Comment.new] + + form_for(:post, @post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + f.fields_for(:comments, comment) do |cf| + concat cf.text_field(:name) + end + end + end + + expected = '<form action="http://www.example.com" method="post">' + + '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + + '</form>' + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_for_on_a_nested_attributes_collection_association_yields_only_builder + @post.comments = [Comment.new(321), Comment.new] + yielded_comments = [] + + form_for(:post, @post) do |f| + concat f.text_field(:title) + f.fields_for(:comments) do |cf| + concat cf.text_field(:name) + yielded_comments << cf.object + end + end + + expected = '<form action="http://www.example.com" method="post">' + + '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + + '</form>' + + assert_dom_equal expected, output_buffer + assert_equal yielded_comments, @post.comments + end + + def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association + @post.comments = [] + + form_for(:post, @post) do |f| + f.fields_for(:comments, Comment.new(321), :child_index => 'abc') do |cf| + concat cf.text_field(:name) + end + end + + expected = '<form action="http://www.example.com" method="post">' + + '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />' + + '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" size="30" type="text" value="comment #321" />' + + '</form>' + + assert_dom_equal expected, output_buffer + end + def test_fields_for fields_for(:post, @post) do |f| concat f.text_field(:title) @@ -569,8 +731,8 @@ class FormHelperTest < ActionView::TestCase expected = "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' type='hidden' value='0' />" + + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" assert_dom_equal expected, output_buffer end @@ -585,8 +747,8 @@ class FormHelperTest < ActionView::TestCase expected = "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" + - "<input name='post[123][secret]' type='hidden' value='0' />" + "<input name='post[123][secret]' type='hidden' value='0' />" + + "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" assert_dom_equal expected, output_buffer end @@ -601,8 +763,8 @@ class FormHelperTest < ActionView::TestCase expected = "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" + "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" + - "<input name='post[][secret]' type='hidden' value='0' />" + "<input name='post[][secret]' type='hidden' value='0' />" + + "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" assert_dom_equal expected, output_buffer end @@ -617,8 +779,8 @@ class FormHelperTest < ActionView::TestCase expected = "<input name='post[abc][title]' size='30' type='text' id='post_abc_title' value='Hello World' />" + "<textarea name='post[abc][body]' id='post_abc_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />" + - "<input name='post[abc][secret]' type='hidden' value='0' />" + "<input name='post[abc][secret]' type='hidden' value='0' />" + + "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />" assert_dom_equal expected, output_buffer end @@ -633,8 +795,8 @@ class FormHelperTest < ActionView::TestCase expected = "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' type='hidden' value='0' />" + + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" assert_dom_equal expected, output_buffer end @@ -649,8 +811,8 @@ class FormHelperTest < ActionView::TestCase expected = "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' type='hidden' value='0' />" + + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" assert_dom_equal expected, output_buffer end @@ -695,8 +857,8 @@ class FormHelperTest < ActionView::TestCase "<form action='http://www.example.com' id='create-post' method='post'>" + "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />" + "<input name='parent_post[secret]' type='hidden' value='0' />" + + "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />" + "</form>" assert_dom_equal expected, output_buffer @@ -744,8 +906,7 @@ class FormHelperTest < ActionView::TestCase "<form action='http://www.example.com' method='post'>" + "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='post[secret]' type='hidden' value='0' /><br/>" + + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + "</form>" assert_dom_equal expected, output_buffer @@ -765,8 +926,7 @@ class FormHelperTest < ActionView::TestCase "<form action='http://www.example.com' method='post'>" + "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='post[secret]' type='hidden' value='0' /><br/>" + + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + "</form>" assert_dom_equal expected, output_buffer @@ -821,8 +981,7 @@ class FormHelperTest < ActionView::TestCase %(<form action="http://www.example.com" onsubmit="new Ajax.Request('http://www.example.com', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" method="post">) + "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='post[secret]' type='hidden' value='0' /><br/>" + + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + "</form>" assert_dom_equal expected, output_buffer @@ -838,12 +997,52 @@ class FormHelperTest < ActionView::TestCase expected = "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='post[secret]' type='hidden' value='0' /><br/>" + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" assert_dom_equal expected, output_buffer 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>" @@ -975,4 +1174,4 @@ class FormHelperTest < ActionView::TestCase def protect_against_forgery? false end -end +end
\ No newline at end of file diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb index 6821832ee9..78db87971b 100644 --- a/actionpack/test/template/form_options_helper_test.rb +++ b/actionpack/test/template/form_options_helper_test.rb @@ -3,727 +3,749 @@ require 'tzinfo' TZInfo::Timezone.cattr_reader :loaded_zones -uses_mocha "FormOptionsHelperTest" do - class FormOptionsHelperTest < ActionView::TestCase - tests ActionView::Helpers::FormOptionsHelper - - silence_warnings do - Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin) - Continent = Struct.new('Continent', :continent_name, :countries) - Country = Struct.new('Country', :country_id, :country_name) - Firm = Struct.new('Firm', :time_zone) - Album = Struct.new('Album', :id, :title, :genre) - end +class FormOptionsHelperTest < ActionView::TestCase + tests ActionView::Helpers::FormOptionsHelper + + silence_warnings do + Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin) + Continent = Struct.new('Continent', :continent_name, :countries) + Country = Struct.new('Country', :country_id, :country_name) + Firm = Struct.new('Firm', :time_zone) + Album = Struct.new('Album', :id, :title, :genre) + end - def setup - super - @fake_timezones = %w(A B C D E).inject([]) do |zones, id| - tz = TZInfo::Timezone.loaded_zones[id] = stub(:name => id, :to_s => id) - ActiveSupport::TimeZone.stubs(:[]).with(id).returns(tz) - zones << tz - end - ActiveSupport::TimeZone.stubs(:all).returns(@fake_timezones) + def setup + @fake_timezones = %w(A B C D E).inject([]) do |zones, id| + tz = TZInfo::Timezone.loaded_zones[id] = stub(:name => id, :to_s => id) + ActiveSupport::TimeZone.stubs(:[]).with(id).returns(tz) + zones << tz end + ActiveSupport::TimeZone.stubs(:all).returns(@fake_timezones) + end - def test_collection_options - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + def test_collection_options + assert_dom_equal( + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title") + ) + end + + def test_collection_options_with_preselected_value + assert_dom_equal( + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title", "Babe") + ) + end + + def test_collection_options_with_preselected_value_array assert_dom_equal( - "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", - options_from_collection_for_select(@posts, "author_name", "title") + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title", [ "Babe", "Cabe" ]) ) - end + end + def test_collection_options_with_proc_for_selected + assert_dom_equal( + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title", lambda{|p| p.author_name == 'Babe' }) + ) + end - def test_collection_options_with_preselected_value - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + def test_collection_options_with_disabled_value + assert_dom_equal( + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => "Babe") + ) + end - assert_dom_equal( - "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", - options_from_collection_for_select(@posts, "author_name", "title", "Babe") - ) - end + def test_collection_options_with_disabled_array + assert_dom_equal( + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => [ "Babe", "Cabe" ]) + ) + end - def test_collection_options_with_preselected_value_array - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] - - assert_dom_equal( - "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>", - options_from_collection_for_select(@posts, "author_name", "title", [ "Babe", "Cabe" ]) - ) - end + def test_collection_options_with_preselected_and_disabled_value + assert_dom_equal( + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title", :selected => "Cabe", :disabled => "Babe") + ) + end - def test_array_options_for_select - assert_dom_equal( - "<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\">USA</option>\n<option value=\"Sweden\">Sweden</option>", - options_for_select([ "<Denmark>", "USA", "Sweden" ]) - ) - end + def test_collection_options_with_proc_for_disabled + assert_dom_equal( + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda{|p| %w(Babe Cabe).include? p.author_name }) + ) + end + + def test_array_options_for_select + assert_dom_equal( + "<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\">USA</option>\n<option value=\"Sweden\">Sweden</option>", + options_for_select([ "<Denmark>", "USA", "Sweden" ]) + ) + end - def test_array_options_for_select_with_selection + def test_array_options_for_select_with_selection + assert_dom_equal( + "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\">Sweden</option>", + options_for_select([ "Denmark", "<USA>", "Sweden" ], "<USA>") + ) + end + + def test_array_options_for_select_with_selection_array assert_dom_equal( - "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\">Sweden</option>", - options_for_select([ "Denmark", "<USA>", "Sweden" ], "<USA>") + "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>", + options_for_select([ "Denmark", "<USA>", "Sweden" ], [ "<USA>", "Sweden" ]) ) - end + end - def test_array_options_for_select_with_selection_array - assert_dom_equal( - "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>", - options_for_select([ "Denmark", "<USA>", "Sweden" ], [ "<USA>", "Sweden" ]) - ) - end + def test_array_options_for_select_with_disabled_value + assert_dom_equal( + "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\">Sweden</option>", + options_for_select([ "Denmark", "<USA>", "Sweden" ], :disabled => "<USA>") + ) + end - def test_array_options_for_string_include_in_other_string_bug_fix - assert_dom_equal( - "<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>", - options_for_select([ "ruby", "rubyonrails" ], "rubyonrails") - ) - assert_dom_equal( - "<option value=\"ruby\" selected=\"selected\">ruby</option>\n<option value=\"rubyonrails\">rubyonrails</option>", - options_for_select([ "ruby", "rubyonrails" ], "ruby") - ) - assert_dom_equal( - %(<option value="ruby" selected="selected">ruby</option>\n<option value="rubyonrails">rubyonrails</option>\n<option value=""></option>), - options_for_select([ "ruby", "rubyonrails", nil ], "ruby") - ) - end + def test_array_options_for_select_with_disabled_array + assert_dom_equal( + "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\" disabled=\"disabled\">Sweden</option>", + options_for_select([ "Denmark", "<USA>", "Sweden" ], :disabled => ["<USA>", "Sweden"]) + ) + end - def test_hash_options_for_select - assert_dom_equal( - "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\">$</option>", - options_for_select("$" => "Dollar", "<DKR>" => "<Kroner>").split("\n").sort.join("\n") - ) - assert_dom_equal( - "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>", - options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, "Dollar").split("\n").sort.join("\n") - ) - assert_dom_equal( - "<option value=\"<Kroner>\" selected=\"selected\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>", - options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, [ "Dollar", "<Kroner>" ]).split("\n").sort.join("\n") - ) - end + def test_array_options_for_select_with_selection_and_disabled_value + assert_dom_equal( + "<option value=\"Denmark\" selected=\"selected\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\">Sweden</option>", + options_for_select([ "Denmark", "<USA>", "Sweden" ], :selected => "Denmark", :disabled => "<USA>") + ) + end - def test_ducktyped_options_for_select - quack = Struct.new(:first, :last) + def test_array_options_for_string_include_in_other_string_bug_fix assert_dom_equal( - "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\">$</option>", - options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")]) + "<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>", + options_for_select([ "ruby", "rubyonrails" ], "rubyonrails") ) assert_dom_equal( - "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>", - options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], "Dollar") + "<option value=\"ruby\" selected=\"selected\">ruby</option>\n<option value=\"rubyonrails\">rubyonrails</option>", + options_for_select([ "ruby", "rubyonrails" ], "ruby") ) assert_dom_equal( - "<option value=\"<Kroner>\" selected=\"selected\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>", - options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], ["Dollar", "<Kroner>"]) + %(<option value="ruby" selected="selected">ruby</option>\n<option value="rubyonrails">rubyonrails</option>\n<option value=""></option>), + options_for_select([ "ruby", "rubyonrails", nil ], "ruby") ) - end - - def test_option_groups_from_collection_for_select - @continents = [ - Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")] ), - Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")] ) - ] + end - assert_dom_equal( - "<optgroup label=\"<Africa>\"><option value=\"<sa>\"><South Africa></option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>", - option_groups_from_collection_for_select(@continents, "countries", "continent_name", "country_id", "country_name", "dk") - ) - end + def test_hash_options_for_select + assert_dom_equal( + "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\">$</option>", + options_for_select("$" => "Dollar", "<DKR>" => "<Kroner>").split("\n").sort.join("\n") + ) + assert_dom_equal( + "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>", + options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, "Dollar").split("\n").sort.join("\n") + ) + assert_dom_equal( + "<option value=\"<Kroner>\" selected=\"selected\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>", + options_for_select({ "$" => "Dollar", "<DKR>" => "<Kroner>" }, [ "Dollar", "<Kroner>" ]).split("\n").sort.join("\n") + ) + end - def test_grouped_options_for_select_with_array - assert_dom_equal( - "<optgroup label=\"North America\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>", - grouped_options_for_select([ - ["North America", - [['United States','US'],"Canada"]], - ["Europe", - [["Great Britain","GB"], "Germany"]] - ]) - ) - end + def test_ducktyped_options_for_select + quack = Struct.new(:first, :last) + assert_dom_equal( + "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\">$</option>", + options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")]) + ) + assert_dom_equal( + "<option value=\"<Kroner>\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>", + options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], "Dollar") + ) + assert_dom_equal( + "<option value=\"<Kroner>\" selected=\"selected\"><DKR></option>\n<option value=\"Dollar\" selected=\"selected\">$</option>", + options_for_select([quack.new("<DKR>", "<Kroner>"), quack.new("$", "Dollar")], ["Dollar", "<Kroner>"]) + ) + end - def test_grouped_options_for_select_with_selected_and_prompt - assert_dom_equal( - "<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>", - grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", "Choose a product...") - ) - end + def test_option_groups_from_collection_for_select + @continents = [ + Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")] ), + Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")] ) + ] - def test_optgroups_with_with_options_with_hash - assert_dom_equal( - "<optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup><optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup>", - grouped_options_for_select({'North America' => ['United States','Canada'], 'Europe' => ['Denmark','Germany']}) - ) - end + assert_dom_equal( + "<optgroup label=\"<Africa>\"><option value=\"<sa>\"><South Africa></option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>", + option_groups_from_collection_for_select(@continents, "countries", "continent_name", "country_id", "country_name", "dk") + ) + end - def test_time_zone_options_no_parms - opts = time_zone_options_for_select - assert_dom_equal "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\">D</option>\n" + - "<option value=\"E\">E</option>", - opts - end + def test_grouped_options_for_select_with_array + assert_dom_equal( + "<optgroup label=\"North America\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>", + grouped_options_for_select([ + ["North America", + [['United States','US'],"Canada"]], + ["Europe", + [["Great Britain","GB"], "Germany"]] + ]) + ) + end - def test_time_zone_options_with_selected - opts = time_zone_options_for_select( "D" ) - assert_dom_equal "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>", - opts - end + def test_grouped_options_for_select_with_selected_and_prompt + assert_dom_equal( + "<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>", + grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", "Choose a product...") + ) + end - def test_time_zone_options_with_unknown_selected - opts = time_zone_options_for_select( "K" ) - assert_dom_equal "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\">D</option>\n" + - "<option value=\"E\">E</option>", - opts - end + def test_optgroups_with_with_options_with_hash + assert_dom_equal( + "<optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup><optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup>", + grouped_options_for_select({'North America' => ['United States','Canada'], 'Europe' => ['Denmark','Germany']}) + ) + end - def test_time_zone_options_with_priority_zones - zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] - opts = time_zone_options_for_select( nil, zones ) - assert_dom_equal "<option value=\"B\">B</option>\n" + - "<option value=\"E\">E</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\">D</option>", - opts - end + def test_time_zone_options_no_parms + opts = time_zone_options_for_select + assert_dom_equal "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\">D</option>\n" + + "<option value=\"E\">E</option>", + opts + end - def test_time_zone_options_with_selected_priority_zones - zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] - opts = time_zone_options_for_select( "E", zones ) - assert_dom_equal "<option value=\"B\">B</option>\n" + - "<option value=\"E\" selected=\"selected\">E</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\">D</option>", - opts - end + def test_time_zone_options_with_selected + opts = time_zone_options_for_select( "D" ) + assert_dom_equal "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>", + opts + end - def test_time_zone_options_with_unselected_priority_zones - zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] - opts = time_zone_options_for_select( "C", zones ) - assert_dom_equal "<option value=\"B\">B</option>\n" + - "<option value=\"E\">E</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"C\" selected=\"selected\">C</option>\n" + - "<option value=\"D\">D</option>", - opts - end + def test_time_zone_options_with_unknown_selected + opts = time_zone_options_for_select( "K" ) + assert_dom_equal "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\">D</option>\n" + + "<option value=\"E\">E</option>", + opts + end - def test_select - @post = Post.new - @post.category = "<mus>" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest)) - ) - end + def test_time_zone_options_with_priority_zones + zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] + opts = time_zone_options_for_select( nil, zones ) + assert_dom_equal "<option value=\"B\">B</option>\n" + + "<option value=\"E\">E</option>" + + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + + "<option value=\"A\">A</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\">D</option>", + opts + end - def test_select_under_fields_for - @post = Post.new - @post.category = "<mus>" + def test_time_zone_options_with_selected_priority_zones + zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] + opts = time_zone_options_for_select( "E", zones ) + assert_dom_equal "<option value=\"B\">B</option>\n" + + "<option value=\"E\" selected=\"selected\">E</option>" + + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + + "<option value=\"A\">A</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\">D</option>", + opts + end - fields_for :post, @post do |f| - concat f.select(:category, %w( abe <mus> hest)) - end - - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - output_buffer - ) - end + def test_time_zone_options_with_unselected_priority_zones + zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] + opts = time_zone_options_for_select( "C", zones ) + assert_dom_equal "<option value=\"B\">B</option>\n" + + "<option value=\"E\">E</option>" + + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + + "<option value=\"A\">A</option>\n" + + "<option value=\"C\" selected=\"selected\">C</option>\n" + + "<option value=\"D\">D</option>", + opts + end - def test_select_under_fields_for_with_index - @post = Post.new - @post.category = "<mus>" + def test_select + @post = Post.new + @post.category = "<mus>" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest)) + ) + end - fields_for :post, @post, :index => 108 do |f| - concat f.select(:category, %w( abe <mus> hest)) - end + def test_select_under_fields_for + @post = Post.new + @post.category = "<mus>" - assert_dom_equal( - "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - output_buffer - ) + fields_for :post, @post do |f| + concat f.select(:category, %w( abe <mus> hest)) end + + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", + output_buffer + ) + end - def test_select_under_fields_for_with_auto_index - @post = Post.new - @post.category = "<mus>" - def @post.to_param; 108; end - - fields_for "post[]", @post do |f| - concat f.select(:category, %w( abe <mus> hest)) - end + def test_select_under_fields_for_with_index + @post = Post.new + @post.category = "<mus>" - assert_dom_equal( - "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - output_buffer - ) + fields_for :post, @post, :index => 108 do |f| + concat f.select(:category, %w( abe <mus> hest)) end - def test_select_with_blank - @post = Post.new - @post.category = "<mus>" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :include_blank => true) - ) - end + assert_dom_equal( + "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", + output_buffer + ) + end - def test_select_with_blank_as_string - @post = Post.new - @post.category = "<mus>" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">None</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :include_blank => 'None') - ) - end + def test_select_under_fields_for_with_auto_index + @post = Post.new + @post.category = "<mus>" + def @post.to_param; 108; end - def test_select_with_default_prompt - @post = Post.new - @post.category = "" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => true) - ) + fields_for "post[]", @post do |f| + concat f.select(:category, %w( abe <mus> hest)) end - def test_select_no_prompt_when_select_has_value - @post = Post.new - @post.category = "<mus>" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => true) - ) - end + assert_dom_equal( + "<select id=\"post_108_category\" name=\"post[108][category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", + output_buffer + ) + end - def test_select_with_given_prompt - @post = Post.new - @post.category = "" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => 'The prompt') - ) - end + def test_select_with_blank + @post = Post.new + @post.category = "<mus>" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest), :include_blank => true) + ) + end - def test_select_with_prompt_and_blank - @post = Post.new - @post.category = "" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => true, :include_blank => true) - ) - end + def test_select_with_blank_as_string + @post = Post.new + @post.category = "<mus>" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">None</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest), :include_blank => 'None') + ) + end - def test_select_with_selected_value - @post = Post.new - @post.category = "<mus>" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" selected=\"selected\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest ), :selected => 'abe') - ) - end - - def test_select_with_index_option - @album = Album.new - @album.id = 1 - - expected = "<select id=\"album__genre\" name=\"album[][genre]\"><option value=\"rap\">rap</option>\n<option value=\"rock\">rock</option>\n<option value=\"country\">country</option></select>" + def test_select_with_default_prompt + @post = Post.new + @post.category = "" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest), :prompt => true) + ) + end - assert_dom_equal( - expected, - select("album[]", "genre", %w[rap rock country], {}, { :index => nil }) - ) - end + def test_select_no_prompt_when_select_has_value + @post = Post.new + @post.category = "<mus>" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest), :prompt => true) + ) + end - def test_select_with_selected_nil - @post = Post.new - @post.category = "<mus>" - assert_dom_equal( - "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest ), :selected => nil) - ) - end + def test_select_with_given_prompt + @post = Post.new + @post.category = "" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest), :prompt => 'The prompt') + ) + end - def test_collection_select - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + def test_select_with_prompt_and_blank + @post = Post.new + @post.category = "" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest), :prompt => true, :include_blank => true) + ) + end - @post = Post.new - @post.author_name = "Babe" + def test_select_with_selected_value + @post = Post.new + @post.category = "<mus>" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" selected=\"selected\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest ), :selected => 'abe') + ) + end - assert_dom_equal( - "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", - collection_select("post", "author_name", @posts, "author_name", "author_name") - ) - end + def test_select_with_index_option + @album = Album.new + @album.id = 1 + + expected = "<select id=\"album__genre\" name=\"album[][genre]\"><option value=\"rap\">rap</option>\n<option value=\"rock\">rock</option>\n<option value=\"country\">country</option></select>" - def test_collection_select_under_fields_for - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + assert_dom_equal( + expected, + select("album[]", "genre", %w[rap rock country], {}, { :index => nil }) + ) + end - @post = Post.new - @post.author_name = "Babe" + def test_select_with_selected_nil + @post = Post.new + @post.category = "<mus>" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", + select("post", "category", %w( abe <mus> hest ), :selected => nil) + ) + end - fields_for :post, @post do |f| - concat f.collection_select(:author_name, @posts, :author_name, :author_name) - end - - assert_dom_equal( - "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", - output_buffer - ) - end + def test_select_with_disabled_value + @post = Post.new + @post.category = "<mus>" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>", + select("post", "category", %w( abe <mus> hest ), :disabled => 'hest') + ) + end - def test_collection_select_under_fields_for_with_index - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + def test_select_with_disabled_array + @post = Post.new + @post.category = "<mus>" + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" disabled=\"disabled\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>", + select("post", "category", %w( abe <mus> hest ), :disabled => ['hest', 'abe']) + ) + end - @post = Post.new - @post.author_name = "Babe" + def test_collection_select + @post = Post.new + @post.author_name = "Babe" - fields_for :post, @post, :index => 815 do |f| - concat f.collection_select(:author_name, @posts, :author_name, :author_name) - end + assert_dom_equal( + "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", + collection_select("post", "author_name", dummy_posts, "author_name", "author_name") + ) + end - assert_dom_equal( - "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", - output_buffer - ) + def test_collection_select_under_fields_for + @post = Post.new + @post.author_name = "Babe" + + fields_for :post, @post do |f| + concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name) end + + assert_dom_equal( + "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", + output_buffer + ) + end - def test_collection_select_under_fields_for_with_auto_index - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + def test_collection_select_under_fields_for_with_index + @post = Post.new + @post.author_name = "Babe" - @post = Post.new - @post.author_name = "Babe" - def @post.to_param; 815; end + fields_for :post, @post, :index => 815 do |f| + concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name) + end - fields_for "post[]", @post do |f| - concat f.collection_select(:author_name, @posts, :author_name, :author_name) - end + assert_dom_equal( + "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", + output_buffer + ) + end - assert_dom_equal( - "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", - output_buffer - ) + def test_collection_select_under_fields_for_with_auto_index + @post = Post.new + @post.author_name = "Babe" + def @post.to_param; 815; end + + fields_for "post[]", @post do |f| + concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name) end - def test_collection_select_with_blank_and_style - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + assert_dom_equal( + "<select id=\"post_815_author_name\" name=\"post[815][author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", + output_buffer + ) + end - @post = Post.new - @post.author_name = "Babe" + def test_collection_select_with_blank_and_style + @post = Post.new + @post.author_name = "Babe" - assert_dom_equal( - "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", - collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true }, "style" => "width: 200px") - ) - end + assert_dom_equal( + "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", + collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true }, "style" => "width: 200px") + ) + end - def test_collection_select_with_blank_as_string_and_style - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + def test_collection_select_with_blank_as_string_and_style + @post = Post.new + @post.author_name = "Babe" - @post = Post.new - @post.author_name = "Babe" + assert_dom_equal( + "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\">No Selection</option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", + collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => 'No Selection' }, "style" => "width: 200px") + ) + end - assert_dom_equal( - "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\">No Selection</option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", - collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => 'No Selection' }, "style" => "width: 200px") - ) - end + def test_collection_select_with_multiple_option_appends_array_brackets + @post = Post.new + @post.author_name = "Babe" - def test_collection_select_with_multiple_option_appends_array_brackets - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + expected = "<select id=\"post_author_name\" name=\"post[author_name][]\" multiple=\"multiple\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>" - @post = Post.new - @post.author_name = "Babe" + # Should suffix default name with []. + assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true }, :multiple => true) - expected = "<select id=\"post_author_name\" name=\"post[author_name][]\" multiple=\"multiple\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>" + # Shouldn't suffix custom name with []. + assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true, :name => 'post[author_name][]' }, :multiple => true) + end - # Should suffix default name with []. - assert_dom_equal expected, collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true }, :multiple => true) + def test_collection_select_with_blank_and_selected + @post = Post.new + @post.author_name = "Babe" - # Shouldn't suffix custom name with []. - assert_dom_equal expected, collection_select("post", "author_name", @posts, "author_name", "author_name", { :include_blank => true, :name => 'post[author_name][]' }, :multiple => true) - end + assert_dom_equal( + %{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="<Abe>" selected="selected"><Abe></option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>}, + collection_select("post", "author_name", dummy_posts, "author_name", "author_name", {:include_blank => true, :selected => "<Abe>"}) + ) + end - def test_collection_select_with_blank_and_selected - @posts = [ - Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") - ] + def test_collection_select_with_disabled + @post = Post.new + @post.author_name = "Babe" - @post = Post.new - @post.author_name = "Babe" + assert_dom_equal( + "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe</option></select>", + collection_select("post", "author_name", dummy_posts, "author_name", "author_name", :disabled => 'Cabe') + ) + end - assert_dom_equal( - %{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="<Abe>" selected="selected"><Abe></option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>}, - collection_select("post", "author_name", @posts, "author_name", "author_name", {:include_blank => true, :selected => "<Abe>"}) - ) - end + def test_time_zone_select + @firm = Firm.new("D") + html = time_zone_select( "firm", "time_zone" ) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + html + end - def test_time_zone_select - @firm = Firm.new("D") - html = time_zone_select( "firm", "time_zone" ) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html + def test_time_zone_select_under_fields_for + @firm = Firm.new("D") + + fields_for :firm, @firm do |f| + concat f.time_zone_select(:time_zone) end + + assert_dom_equal( + "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + output_buffer + ) + end - def test_time_zone_select_under_fields_for - @firm = Firm.new("D") + def test_time_zone_select_under_fields_for_with_index + @firm = Firm.new("D") - fields_for :firm, @firm do |f| - concat f.time_zone_select(:time_zone) - end - - assert_dom_equal( - "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - output_buffer - ) + fields_for :firm, @firm, :index => 305 do |f| + concat f.time_zone_select(:time_zone) end - def test_time_zone_select_under_fields_for_with_index - @firm = Firm.new("D") + assert_dom_equal( + "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + output_buffer + ) + end - fields_for :firm, @firm, :index => 305 do |f| - concat f.time_zone_select(:time_zone) - end + def test_time_zone_select_under_fields_for_with_auto_index + @firm = Firm.new("D") + def @firm.to_param; 305; end - assert_dom_equal( - "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - output_buffer - ) + fields_for "firm[]", @firm do |f| + concat f.time_zone_select(:time_zone) end - def test_time_zone_select_under_fields_for_with_auto_index - @firm = Firm.new("D") - def @firm.to_param; 305; end + assert_dom_equal( + "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + output_buffer + ) + end - fields_for "firm[]", @firm do |f| - concat f.time_zone_select(:time_zone) - end + def test_time_zone_select_with_blank + @firm = Firm.new("D") + html = time_zone_select("firm", "time_zone", nil, :include_blank => true) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + + "<option value=\"\"></option>\n" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + html + end - assert_dom_equal( - "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - output_buffer - ) - end + def test_time_zone_select_with_blank_as_string + @firm = Firm.new("D") + html = time_zone_select("firm", "time_zone", nil, :include_blank => 'No Zone') + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + + "<option value=\"\">No Zone</option>\n" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + html + end - def test_time_zone_select_with_blank - @firm = Firm.new("D") - html = time_zone_select("firm", "time_zone", nil, :include_blank => true) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"\"></option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html - end + def test_time_zone_select_with_style + @firm = Firm.new("D") + html = time_zone_select("firm", "time_zone", nil, {}, + "style" => "color: red") + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + html + assert_dom_equal html, time_zone_select("firm", "time_zone", nil, {}, + :style => "color: red") + end - def test_time_zone_select_with_blank_as_string - @firm = Firm.new("D") - html = time_zone_select("firm", "time_zone", nil, :include_blank => 'No Zone') - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"\">No Zone</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html - end + def test_time_zone_select_with_blank_and_style + @firm = Firm.new("D") + html = time_zone_select("firm", "time_zone", nil, + { :include_blank => true }, "style" => "color: red") + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + + "<option value=\"\"></option>\n" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + html + assert_dom_equal html, time_zone_select("firm", "time_zone", nil, + { :include_blank => true }, :style => "color: red") + end - def test_time_zone_select_with_style - @firm = Firm.new("D") - html = time_zone_select("firm", "time_zone", nil, {}, - "style" => "color: red") - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html - assert_dom_equal html, time_zone_select("firm", "time_zone", nil, {}, - :style => "color: red") - end + def test_time_zone_select_with_blank_as_string_and_style + @firm = Firm.new("D") + html = time_zone_select("firm", "time_zone", nil, + { :include_blank => 'No Zone' }, "style" => "color: red") + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + + "<option value=\"\">No Zone</option>\n" + + "<option value=\"A\">A</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + html + assert_dom_equal html, time_zone_select("firm", "time_zone", nil, + { :include_blank => 'No Zone' }, :style => "color: red") + end - def test_time_zone_select_with_blank_and_style - @firm = Firm.new("D") - html = time_zone_select("firm", "time_zone", nil, - { :include_blank => true }, "style" => "color: red") - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + - "<option value=\"\"></option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html - assert_dom_equal html, time_zone_select("firm", "time_zone", nil, - { :include_blank => true }, :style => "color: red") - end + def test_time_zone_select_with_priority_zones + @firm = Firm.new("D") + zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ] + html = time_zone_select("firm", "time_zone", zones ) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + + "<option value=\"A\">A</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>" + + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + html + end - def test_time_zone_select_with_blank_as_string_and_style - @firm = Firm.new("D") - html = time_zone_select("firm", "time_zone", nil, - { :include_blank => 'No Zone' }, "style" => "color: red") - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + - "<option value=\"\">No Zone</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html - assert_dom_equal html, time_zone_select("firm", "time_zone", nil, - { :include_blank => 'No Zone' }, :style => "color: red") - end + def test_time_zone_select_with_priority_zones_as_regexp + @firm = Firm.new("D") + @fake_timezones.each_with_index do |tz, i| + tz.stubs(:=~).returns(i.zero? || i == 3) + end + + html = time_zone_select("firm", "time_zone", /A|D/) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + + "<option value=\"A\">A</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>" + + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + + "<option value=\"B\">B</option>\n" + + "<option value=\"C\">C</option>\n" + + "<option value=\"E\">E</option>" + + "</select>", + html + end - def test_time_zone_select_with_priority_zones - @firm = Firm.new("D") - zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ] - html = time_zone_select("firm", "time_zone", zones ) + def test_time_zone_select_with_default_time_zone_and_nil_value + @firm = Firm.new() + @firm.time_zone = nil + html = time_zone_select( "firm", "time_zone", nil, :default => 'B' ) assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + "<option value=\"A\">A</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"B\">B</option>\n" + + "<option value=\"B\" selected=\"selected\">B</option>\n" + "<option value=\"C\">C</option>\n" + + "<option value=\"D\">D</option>\n" + "<option value=\"E\">E</option>" + "</select>", html - end - - def test_time_zone_select_with_priority_zones_as_regexp - @firm = Firm.new("D") - @fake_timezones.each_with_index do |tz, i| - tz.stubs(:=~).returns(i.zero? || i == 3) - end + end - html = time_zone_select("firm", "time_zone", /A|D/) + def test_time_zone_select_with_default_time_zone_and_value + @firm = Firm.new('D') + html = time_zone_select( "firm", "time_zone", nil, :default => 'B' ) assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + "<option value=\"A\">A</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + "<option value=\"B\">B</option>\n" + "<option value=\"C\">C</option>\n" + + "<option value=\"D\" selected=\"selected\">D</option>\n" + "<option value=\"E\">E</option>" + "</select>", html - end + end - def test_time_zone_select_with_default_time_zone_and_nil_value - @firm = Firm.new() - @firm.time_zone = nil - html = time_zone_select( "firm", "time_zone", nil, :default => 'B' ) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\" selected=\"selected\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html - end + private - def test_time_zone_select_with_default_time_zone_and_value - @firm = Firm.new('D') - html = time_zone_select( "firm", "time_zone", nil, :default => 'B' ) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html + def dummy_posts + [ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), + Post.new("Babe went home", "Babe", "To a little house", "shh!"), + Post.new("Cabe went home", "Cabe", "To a little house", "shh!") ] end - - end end diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index 9d4dac64f2..ea0be4a27a 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -267,11 +267,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 cf79480ab5..f9bc92c7c9 100644 --- a/actionpack/test/template/javascript_helper_test.rb +++ b/actionpack/test/template/javascript_helper_test.rb @@ -46,11 +46,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_i18n_test.rb b/actionpack/test/template/number_helper_i18n_test.rb index 3fdf991a44..bf5b81292f 100644 --- a/actionpack/test/template/number_helper_i18n_test.rb +++ b/actionpack/test/template/number_helper_i18n_test.rb @@ -5,67 +5,65 @@ class NumberHelperI18nTests < Test::Unit::TestCase attr_reader :request - uses_mocha 'number_helper_i18n_tests' do - def setup - @number_defaults = { :precision => 3, :delimiter => ',', :separator => '.' } - @currency_defaults = { :unit => '$', :format => '%u%n', :precision => 2 } - @human_defaults = { :precision => 1 } - @human_storage_units_format_default = "%n %u" - @human_storage_units_units_byte_other = "Bytes" - @human_storage_units_units_kb_other = "KB" - @percentage_defaults = { :delimiter => '' } - @precision_defaults = { :delimiter => '' } + def setup + @number_defaults = { :precision => 3, :delimiter => ',', :separator => '.' } + @currency_defaults = { :unit => '$', :format => '%u%n', :precision => 2 } + @human_defaults = { :precision => 1 } + @human_storage_units_format_default = "%n %u" + @human_storage_units_units_byte_other = "Bytes" + @human_storage_units_units_kb_other = "KB" + @percentage_defaults = { :delimiter => '' } + @precision_defaults = { :delimiter => '' } - I18n.backend.store_translations 'en', :number => { :format => @number_defaults, - :currency => { :format => @currency_defaults }, :human => @human_defaults } - end + I18n.backend.store_translations 'en', :number => { :format => @number_defaults, + :currency => { :format => @currency_defaults }, :human => @human_defaults } + end - def test_number_to_currency_translates_currency_formats - I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) - I18n.expects(:translate).with(:'number.currency.format', :locale => 'en', - :raise => true).returns(@currency_defaults) - number_to_currency(1, :locale => 'en') - end + def test_number_to_currency_translates_currency_formats + I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) + I18n.expects(:translate).with(:'number.currency.format', :locale => 'en', + :raise => true).returns(@currency_defaults) + number_to_currency(1, :locale => 'en') + end - def test_number_with_precision_translates_number_formats - I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) - I18n.expects(:translate).with(:'number.precision.format', :locale => 'en', - :raise => true).returns(@precision_defaults) - number_with_precision(1, :locale => 'en') - end + def test_number_with_precision_translates_number_formats + I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) + I18n.expects(:translate).with(:'number.precision.format', :locale => 'en', + :raise => true).returns(@precision_defaults) + number_with_precision(1, :locale => 'en') + end - def test_number_with_delimiter_translates_number_formats - I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) - number_with_delimiter(1, :locale => 'en') - end + def test_number_with_delimiter_translates_number_formats + I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) + number_with_delimiter(1, :locale => 'en') + end - def test_number_to_percentage_translates_number_formats - I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) - I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en', - :raise => true).returns(@percentage_defaults) - number_to_percentage(1, :locale => 'en') - end + def test_number_to_percentage_translates_number_formats + I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) + I18n.expects(:translate).with(:'number.percentage.format', :locale => 'en', + :raise => true).returns(@percentage_defaults) + number_to_percentage(1, :locale => 'en') + end - def test_number_to_human_size_translates_human_formats - I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) - I18n.expects(:translate).with(:'number.human.format', :locale => 'en', - :raise => true).returns(@human_defaults) - I18n.expects(:translate).with(:'number.human.storage_units.format', :locale => 'en', - :raise => true).returns(@human_storage_units_format_default) - I18n.expects(:translate).with(:'number.human.storage_units.units.kb', :locale => 'en', :count => 2, - :raise => true).returns(@human_storage_units_units_kb_other) - # 2KB - number_to_human_size(2048, :locale => 'en') + def test_number_to_human_size_translates_human_formats + I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) + I18n.expects(:translate).with(:'number.human.format', :locale => 'en', + :raise => true).returns(@human_defaults) + I18n.expects(:translate).with(:'number.human.storage_units.format', :locale => 'en', + :raise => true).returns(@human_storage_units_format_default) + I18n.expects(:translate).with(:'number.human.storage_units.units.kb', :locale => 'en', :count => 2, + :raise => true).returns(@human_storage_units_units_kb_other) + # 2KB + number_to_human_size(2048, :locale => 'en') - I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) - I18n.expects(:translate).with(:'number.human.format', :locale => 'en', - :raise => true).returns(@human_defaults) - I18n.expects(:translate).with(:'number.human.storage_units.format', :locale => 'en', - :raise => true).returns(@human_storage_units_format_default) - I18n.expects(:translate).with(:'number.human.storage_units.units.byte', :locale => 'en', :count => 42, - :raise => true).returns(@human_storage_units_units_byte_other) - # 42 Bytes - number_to_human_size(42, :locale => 'en') - end + I18n.expects(:translate).with(:'number.format', :locale => 'en', :raise => true).returns(@number_defaults) + I18n.expects(:translate).with(:'number.human.format', :locale => 'en', + :raise => true).returns(@human_defaults) + I18n.expects(:translate).with(:'number.human.storage_units.format', :locale => 'en', + :raise => true).returns(@human_storage_units_format_default) + I18n.expects(:translate).with(:'number.human.storage_units.units.byte', :locale => 'en', :count => 42, + :raise => true).returns(@human_storage_units_units_byte_other) + # 42 Bytes + number_to_human_size(42, :locale => 'en') end end 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/output_buffer_test.rb b/actionpack/test/template/output_buffer_test.rb new file mode 100644 index 0000000000..6d8eab63dc --- /dev/null +++ b/actionpack/test/template/output_buffer_test.rb @@ -0,0 +1,35 @@ +require 'abstract_unit' + +class OutputBufferTest < ActionController::TestCase + class TestController < ActionController::Base + def index + render :text => 'foo' + end + end + + tests TestController + + def test_flush_output_buffer + # Start with the default body parts + get :index + assert_equal ['foo'], @response.body_parts + assert_nil @response.template.output_buffer + + # Nil output buffer is skipped + @response.template.flush_output_buffer + assert_nil @response.template.output_buffer + assert_equal ['foo'], @response.body_parts + + # Empty output buffer is skipped + @response.template.output_buffer = '' + @response.template.flush_output_buffer + assert_equal '', @response.template.output_buffer + assert_equal ['foo'], @response.body_parts + + # Flushing appends the output buffer to the body parts + @response.template.output_buffer = 'bar' + @response.template.flush_output_buffer + assert_equal '', @response.template.output_buffer + assert_equal ['foo', 'bar'], @response.body_parts + end +end diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index c61191d475..8bad866ce3 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -1,3 +1,4 @@ +# encoding: utf-8 require 'abstract_unit' require 'controller/fake_models' @@ -9,9 +10,10 @@ module RenderTestCases # Reload and register danish language for testing I18n.reload! I18n.backend.store_translations 'da', {} + I18n.backend.store_translations 'pt-BR', {} # Ensure original are still the same since we are reindexing view paths - assert_equal ORIGINAL_LOCALES, I18n.available_locales + assert_equal ORIGINAL_LOCALES, I18n.available_locales.map(&:to_s).sort end def test_render_file @@ -38,6 +40,39 @@ module RenderTestCases end end + def test_render_file_with_dashed_locale + old_locale = I18n.locale + pending do + I18n.locale = :"pt-BR" + assert_equal "Ola mundo", @view.render(:file => "test/hello_world") + end + ensure + I18n.locale = old_locale + end + + def test_render_implicit_html_template_from_xhr_request + old_format = @view.formats + pending do + @view.formats = [:js] + assert_equal "Hello HTML!", @view.render(:file => "test/render_implicit_html_template_from_xhr_request") + end + ensure + @view.formats = old_format + end + + def test_render_implicit_html_template_from_xhr_request_with_localization + old_locale = I18n.locale + old_format = @view.formats + pending do + I18n.locale = :da + @view.formats = [:js] + assert_equal "Hey HTML!\n", @view.render(:file => "test/render_implicit_html_template_from_xhr_request") + end + ensure + I18n.locale = old_locale + @view.formats = old_format + end + def test_render_file_at_top_level assert_equal 'Elastica', @view.render(:file => '/shared') end @@ -120,6 +155,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 @@ -199,6 +238,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") @@ -208,6 +257,14 @@ module RenderTestCases assert_equal %(<title>title</title>\n<div id="column">column</div>\n<div id="content">content</div>\n), @view.render(:file => "test/nested_layout.erb", :layout => "layouts/yield") end + + if '1.9'.respond_to?(:force_encoding) + def test_render_utf8_template + result = @view.render(:file => "test/utf8.html.erb", :layouts => "layouts/yield") + assert_equal "Русский текст\n日本語のテキスト", result + assert_equal Encoding::UTF_8, result.encoding + end + end end class CachedViewRenderTest < ActiveSupport::TestCase diff --git a/actionpack/test/template/test_test.rb b/actionpack/test/template/test_test.rb index c35a264abf..dd07a6d438 100644 --- a/actionpack/test/template/test_test.rb +++ b/actionpack/test/template/test_test.rb @@ -39,12 +39,10 @@ class PeopleHelperTest < ActionView::TestCase assert_equal "http://test.host/people", homepage_url end - uses_mocha "link_to_person" do - def test_link_to_person - person = mock(:name => "David") - expects(:mocha_mock_path).with(person).returns("/people/1") - assert_equal '<a href="/people/1">David</a>', link_to_person(person) - end + def test_link_to_person + person = mock(:name => "David") + expects(:mocha_mock_path).with(person).returns("/people/1") + assert_equal '<a href="/people/1">David</a>', link_to_person(person) end end diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index c420e1f13d..be7163888e 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -376,6 +376,12 @@ class TextHelperTest < ActionView::TestCase assert_equal "{link: #{link3_result}}", auto_link("{link: #{link3_raw}}") end + def test_auto_link_in_tags + link_raw = 'http://www.rubyonrails.org/images/rails.png' + link_result = %Q(<img src="#{link_raw}" />) + assert_equal link_result, auto_link(link_result) + end + def test_auto_link_at_eol url1 = "http://api.rubyonrails.com/Foo.html" url2 = "http://www.ruby-doc.org/core/Bar.html" diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb index d0d65cb450..a20f3c394c 100644 --- a/actionpack/test/template/translation_helper_test.rb +++ b/actionpack/test/template/translation_helper_test.rb @@ -5,24 +5,28 @@ class TranslationHelperTest < Test::Unit::TestCase include ActionView::Helpers::TranslationHelper attr_reader :request - uses_mocha 'translation_helper_test' do - def setup - end - - def test_delegates_to_i18n_setting_the_raise_option - I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true) - translate :foo, :locale => 'en' - end - - def test_returns_missing_translation_message_wrapped_into_span - expected = '<span class="translation_missing">en, foo</span>' - assert_equal expected, translate(:foo) - end + def setup + end + + def test_delegates_to_i18n_setting_the_raise_option + I18n.expects(:translate).with(:foo, :locale => 'en', :raise => true) + translate :foo, :locale => 'en' + end + + def test_returns_missing_translation_message_wrapped_into_span + expected = '<span class="translation_missing">en, foo</span>' + assert_equal expected, translate(:foo) + end + + def test_delegates_localize_to_i18n + @time = Time.utc(2008, 7, 8, 12, 18, 38) + I18n.expects(:localize).with(@time) + localize @time + end - def test_delegates_localize_to_i18n - @time = Time.utc(2008, 7, 8, 12, 18, 38) - I18n.expects(:localize).with(@time) - localize @time - end + def test_scoping_by_partial + expects(:template).returns(stub(:path_without_format_and_extension => "people/index")) + I18n.expects(:translate).with("people.index.foo", :locale => 'en', :raise => true) + translate ".foo", :locale => 'en' end -end
\ No newline at end of file +end diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index c5147c2417..f3d2f87b4a 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -221,7 +221,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 @@ -253,6 +253,27 @@ class UrlHelperTest < ActionView::TestCase assert_equal "Showing", link_to_if(false, "Showing", :action => "show", :controller => "weblog", :id => 1) end + def test_current_page_with_simple_url + @controller.request = RequestMock.new("http://www.example.com/weblog/show") + @controller.url = "http://www.example.com/weblog/show" + assert current_page?({ :action => "show", :controller => "weblog" }) + assert current_page?("http://www.example.com/weblog/show") + end + + def test_current_page_ignoring_params + @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc&page=1") + @controller.url = "http://www.example.com/weblog/show?order=desc&page=1" + assert current_page?({ :action => "show", :controller => "weblog" }) + assert current_page?("http://www.example.com/weblog/show") + end + + def test_current_page_with_params_that_match + @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc&page=1") + @controller.url = "http://www.example.com/weblog/show?order=desc&page=1" + assert current_page?({ :action => "show", :controller => "weblog", :order => "desc", :page => "1" }) + assert current_page?("http://www.example.com/weblog/show?order=desc&page=1") + end + def test_link_unless_current @controller.request = RequestMock.new("http://www.example.com/weblog/show") @controller.url = "http://www.example.com/weblog/show" @@ -264,11 +285,23 @@ class UrlHelperTest < ActionView::TestCase assert_equal "Showing", link_to_unless_current("Showing", { :action => "show", :controller => "weblog" }) assert_equal "Showing", link_to_unless_current("Showing", "http://www.example.com/weblog/show") + @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc&page=1") + @controller.url = "http://www.example.com/weblog/show?order=desc&page=1" + assert_equal "Showing", link_to_unless_current("Showing", { :action => "show", :controller => "weblog", :order=>'desc', :page=>'1' }) + assert_equal "Showing", link_to_unless_current("Showing", "http://www.example.com/weblog/show?order=desc&page=1") + assert_equal "Showing", link_to_unless_current("Showing", "http://www.example.com/weblog/show?order=desc&page=1") + @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc") @controller.url = "http://www.example.com/weblog/show?order=asc" assert_equal "<a href=\"http://www.example.com/weblog/show?order=asc\">Showing</a>", link_to_unless_current("Showing", { :action => "show", :controller => "weblog" }) assert_equal "<a href=\"http://www.example.com/weblog/show?order=asc\">Showing</a>", link_to_unless_current("Showing", "http://www.example.com/weblog/show?order=asc") + @controller.request = RequestMock.new("http://www.example.com/weblog/show?order=desc&page=1") + @controller.url = "http://www.example.com/weblog/show?order=desc&page=2" + assert_equal "<a href=\"http://www.example.com/weblog/show?order=desc&page=2\">Showing</a>", link_to_unless_current("Showing", { :action => "show", :controller => "weblog" }) + assert_equal "<a href=\"http://www.example.com/weblog/show?order=desc&page=2\">Showing</a>", link_to_unless_current("Showing", "http://www.example.com/weblog/show?order=desc&page=2") + + @controller.request = RequestMock.new("http://www.example.com/weblog/show") @controller.url = "http://www.example.com/weblog/list" assert_equal "<a href=\"http://www.example.com/weblog/list\">Listing</a>", @@ -320,7 +353,7 @@ class UrlHelperTest < ActionView::TestCase assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") end - + def protect_against_forgery? false end |