diff options
Diffstat (limited to 'actionpack/lib/action_controller')
22 files changed, 277 insertions, 208 deletions
diff --git a/actionpack/lib/action_controller/assertions/selector_assertions.rb b/actionpack/lib/action_controller/assertions/selector_assertions.rb index 573405c0f9..272b8f6841 100644 --- a/actionpack/lib/action_controller/assertions/selector_assertions.rb +++ b/actionpack/lib/action_controller/assertions/selector_assertions.rb @@ -263,12 +263,15 @@ module ActionController if match_with = equals[:text] matches.delete_if do |match| text = "" + text.force_encoding(match_with.encoding) if text.respond_to?(:force_encoding) stack = match.children.reverse while node = stack.pop if node.tag? stack.concat node.children.reverse else - text << node.content + content = node.content + content.force_encoding(match_with.encoding) if content.respond_to?(:force_encoding) + text << content end end text.strip! unless NO_STRIP.include?(match.name) diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 0c0d0ec4ac..6b5914c4dd 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -277,9 +277,10 @@ module ActionController #:nodoc: @@debug_routes = true cattr_accessor :debug_routes - # Controls whether the application is thread-safe, so multi-threaded servers like WEBrick know whether to apply a mutex - # around the performance of each action. Action Pack and Active Record are by default thread-safe, but many applications - # may not be. Turned off by default. + # Indicates to Mongrel or Webrick whether to allow concurrent action + # processing. Your controller actions and any other code they call must + # also behave well when called from concurrent threads. Turned off by + # default. @@allow_concurrency = false cattr_accessor :allow_concurrency @@ -331,7 +332,8 @@ module ActionController #:nodoc: @@resources_path_names = { :new => 'new', :edit => 'edit' } cattr_accessor :resources_path_names - # Sets the token parameter name for RequestForgery. Calling #protect_from_forgery sets it to :authenticity_token by default + # Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+ + # sets it to <tt>:authenticity_token</tt> by default. cattr_accessor :request_forgery_protection_token # Indicates whether or not optimise the generated named @@ -530,9 +532,9 @@ module ActionController #:nodoc: # Returns a URL that has been rewritten according to the options hash and the defined Routes. # (For doing a complete redirect, use redirect_to). - # + # # <tt>url_for</tt> is used to: - # + # # All keys given to url_for are forwarded to the Route module, save for the following: # * <tt>:anchor</tt> -- specifies the anchor name to be appended to the path. For example, # <tt>url_for :controller => 'posts', :action => 'show', :id => 10, :anchor => 'comments'</tt> @@ -543,8 +545,8 @@ module ActionController #:nodoc: # * <tt>:host</tt> -- overrides the default (current) host if provided. # * <tt>:protocol</tt> -- overrides the default (current) protocol if provided. # * <tt>:port</tt> -- optionally specify the port to connect to. - # * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if :password is also present). - # * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if :user is also present). + # * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present). + # * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present). # * <tt>:skip_relative_url_root</tt> -- if true, the url is not constructed using the relative_url_root of the request so the path # will include the web server relative installation directory. # @@ -597,7 +599,7 @@ module ActionController #:nodoc: # url_for :controller => 'posts', :action => nil # # If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the - # :overwrite_params options. Say for your posts you have different views for showing and printing them. + # <tt>:overwrite_params</tt> options. Say for your posts you have different views for showing and printing them. # Then, in the show view, you get the URL for the print view like this # # url_for :overwrite_params => { :action => 'print' } @@ -768,7 +770,7 @@ module ActionController #:nodoc: # # placed in "app/views/layouts/special.r(html|xml)" # render :text => "Hi there!", :layout => "special" # - # The :text option can also accept a Proc object, which can be used to manually control the page generation. This should + # The <tt>:text</tt> option can also accept a Proc object, which can be used to manually control the page generation. This should # generally be avoided, as it violates the separation between code and content, and because almost everything that can be # done with this method can also be done more cleanly using one of the other rendering methods, most notably templates. # @@ -822,7 +824,7 @@ module ActionController #:nodoc: # # === Rendering with status and location headers # - # All renders take the :status and :location options and turn them into headers. They can even be used together: + # All renders take the <tt>:status</tt> and <tt>:location</tt> options and turn them into headers. They can even be used together: # # render :xml => post.to_xml, :status => :created, :location => post_url(post) def render(options = nil, extra_options = {}, &block) #:doc: diff --git a/actionpack/lib/action_controller/cookies.rb b/actionpack/lib/action_controller/cookies.rb index 19847c6957..a4cddbcea2 100644 --- a/actionpack/lib/action_controller/cookies.rb +++ b/actionpack/lib/action_controller/cookies.rb @@ -1,31 +1,38 @@ module ActionController #:nodoc: - # Cookies are read and written through ActionController#cookies. The cookies being read are what were received along with the request, - # the cookies being written are what will be sent out with the response. Cookies are read by value (so you won't get the cookie object - # itself back -- just the value it holds). Examples for writing: + # Cookies are read and written through ActionController#cookies. # - # cookies[:user_name] = "david" # => Will set a simple session cookie + # The cookies being read are the ones received along with the request, the cookies + # being written will be sent out with the response. Reading a cookie does not get + # the cookie object itself back, just the value it holds. + # + # Examples for writing: + # + # # Sets a simple session cookie. + # cookies[:user_name] = "david" + # + # # Sets a cookie that expires in 1 hour. # cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now } - # # => Will set a cookie that expires in 1 hour # # Examples for reading: # # cookies[:user_name] # => "david" - # cookies.size # => 2 + # cookies.size # => 2 # # Example for deleting: # # cookies.delete :user_name # - # All the option symbols for setting cookies are: + # The option symbols for setting cookies are: # - # * <tt>value</tt> - the cookie's value or list of values (as an array). - # * <tt>path</tt> - the path for which this cookie applies. Defaults to the root of the application. - # * <tt>domain</tt> - the domain for which this cookie applies. - # * <tt>expires</tt> - the time at which this cookie expires, as a +Time+ object. - # * <tt>secure</tt> - whether this cookie is a secure cookie or not (default to false). - # Secure cookies are only transmitted to HTTPS servers. - # * <tt>http_only</tt> - whether this cookie is accessible via scripting or only HTTP (defaults to false). - + # * <tt>:value</tt> - The cookie's value or list of values (as an array). + # * <tt>:path</tt> - The path for which this cookie applies. Defaults to the root + # of the application. + # * <tt>:domain</tt> - The domain for which this cookie applies. + # * <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 + # only HTTP. Defaults to +false+. module Cookies def self.included(base) base.helper_method :cookies @@ -45,8 +52,7 @@ module ActionController #:nodoc: update(@cookies) end - # Returns the value of the cookie by +name+ -- or nil if no such cookie exists. You set new cookies using cookies[]= - # (for simple name/value cookies without options). + # Returns the value of the cookie by +name+, or +nil+ if no such cookie exists. def [](name) cookie = @cookies[name.to_s] if cookie && cookie.respond_to?(:value) @@ -54,6 +60,8 @@ module ActionController #:nodoc: end end + # Sets the cookie named +name+. The second argument may be the very cookie + # value, or a hash of options as documented above. def []=(name, options) if options.is_a?(Hash) options = options.inject({}) { |options, pair| options[pair.first.to_s] = pair.last; options } @@ -66,14 +74,18 @@ module ActionController #:nodoc: end # Removes the cookie on the client machine by setting the value to an empty string - # and setting its expiration date into the past. Like []=, you can pass in an options - # hash to delete cookies with extra data such as a +path+. + # and setting its expiration date into the past. Like <tt>[]=</tt>, you can pass in + # an options hash to delete cookies with extra data such as a <tt>:path</tt>. def delete(name, options = {}) options.stringify_keys! set_cookie(options.merge("name" => name.to_s, "value" => "", "expires" => Time.at(0))) end private + # Builds a CGI::Cookie object and adds the cookie to the response headers. + # + # The path of the cookie defaults to "/" if there's none in +options+, and + # everything is passed to the CGI::Cookie constructor. def set_cookie(options) #:doc: options["path"] = "/" unless options["path"] cookie = CGI::Cookie.new(options) diff --git a/actionpack/lib/action_controller/filters.rb b/actionpack/lib/action_controller/filters.rb index 8c97787741..6d0c83eb40 100644 --- a/actionpack/lib/action_controller/filters.rb +++ b/actionpack/lib/action_controller/filters.rb @@ -126,8 +126,8 @@ module ActionController #:nodoc: # end # # To use a filter object with around_filter, pass an object responding - # to :filter or both :before and :after. With a filter method, yield to - # the block as above: + # to <tt>:filter</tt> or both <tt>:before</tt> and <tt>:after</tt>. With a + # filter method, yield to the block as above: # # around_filter BenchmarkingFilter # @@ -191,8 +191,9 @@ module ActionController #:nodoc: # == Filter conditions # # Filters may be limited to specific actions by declaring the actions to - # include or exclude. Both options accept single actions (:only => :index) - # or arrays of actions (:except => [:foo, :bar]). + # include or exclude. Both options accept single actions + # (<tt>:only => :index</tt>) or arrays of actions + # (<tt>:except => [:foo, :bar]</tt>). # # class Journal < ActionController::Base # # Require authentication for edit and delete. diff --git a/actionpack/lib/action_controller/helpers.rb b/actionpack/lib/action_controller/helpers.rb index 9188f94f37..a8bead4d34 100644 --- a/actionpack/lib/action_controller/helpers.rb +++ b/actionpack/lib/action_controller/helpers.rb @@ -143,11 +143,19 @@ module ActionController #:nodoc: # Declare a controller method as a helper. For example, the following # makes the +current_user+ controller method available to the view: # class ApplicationController < ActionController::Base - # helper_method :current_user + # helper_method :current_user, :logged_in? + # # def current_user - # @current_user ||= User.find(session[:user]) + # @current_user ||= User.find_by_id(session[:user]) # end + # + # def logged_in? + # current_user != nil + # end # end + # + # In a view: + # <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%> def helper_method(*methods) methods.flatten.each do |method| master_helper_module.module_eval <<-end_eval diff --git a/actionpack/lib/action_controller/mime_type.rb b/actionpack/lib/action_controller/mime_type.rb index 16e3ffc9c1..8c02f20521 100644 --- a/actionpack/lib/action_controller/mime_type.rb +++ b/actionpack/lib/action_controller/mime_type.rb @@ -71,8 +71,11 @@ module Mime # keep track of creation order to keep the subsequent sort stable list = [] accept_header.split(/,/).each_with_index do |header, index| - params = header.split(/;\s*q=/) - list << AcceptItem.new(index, *params) unless params.empty? + params, q = header.split(/;\s*q=/) + if params + params.strip! + list << AcceptItem.new(index, params, q) unless params.empty? + end end list.sort! @@ -145,7 +148,7 @@ module Mime end def ==(mime_type) - return false unless mime_type + return false if mime_type.blank? (@synonyms + [ self ]).any? do |synonym| synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym end diff --git a/actionpack/lib/action_controller/polymorphic_routes.rb b/actionpack/lib/action_controller/polymorphic_routes.rb index 2cc2ec7723..aa0e05dbd7 100644 --- a/actionpack/lib/action_controller/polymorphic_routes.rb +++ b/actionpack/lib/action_controller/polymorphic_routes.rb @@ -19,7 +19,7 @@ module ActionController # * <tt>url_for</tt>, so you can use it with a record as the argument, e.g. # <tt>url_for(@article)</tt>; # * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write - # <tt>form_for(@article)</tt> without having to specify :url parameter for the form + # <tt>form_for(@article)</tt> without having to specify <tt>:url</tt> parameter for the form # action; # * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write # <tt>redirect_to(post)</tt> in your controllers; diff --git a/actionpack/lib/action_controller/request.rb b/actionpack/lib/action_controller/request.rb index 823271d13f..d5ecbd9d29 100755 --- a/actionpack/lib/action_controller/request.rb +++ b/actionpack/lib/action_controller/request.rb @@ -15,7 +15,7 @@ module ActionController # such as { 'RAILS_ENV' => 'production' }. attr_reader :env - # The true HTTP request method as a lowercase symbol, such as :get. + # The true HTTP request method as a lowercase symbol, such as <tt>:get</tt>. # UnknownHttpMethod is raised for invalid methods not listed in ACCEPTED_HTTP_METHODS. def request_method @request_method ||= begin @@ -28,35 +28,35 @@ module ActionController end end - # The HTTP request method as a lowercase symbol, such as :get. - # Note, HEAD is returned as :get since the two are functionally + # The HTTP request method as a lowercase symbol, such as <tt>:get</tt>. + # Note, HEAD is returned as <tt>:get</tt> since the two are functionally # equivalent from the application's perspective. def method request_method == :head ? :get : request_method end - # Is this a GET (or HEAD) request? Equivalent to request.method == :get + # Is this a GET (or HEAD) request? Equivalent to <tt>request.method == :get</tt>. def get? method == :get end - # Is this a POST request? Equivalent to request.method == :post + # Is this a POST request? Equivalent to <tt>request.method == :post</tt>. def post? request_method == :post end - # Is this a PUT request? Equivalent to request.method == :put + # Is this a PUT request? Equivalent to <tt>request.method == :put</tt>. def put? request_method == :put end - # Is this a DELETE request? Equivalent to request.method == :delete + # Is this a DELETE request? Equivalent to <tt>request.method == :delete</tt>. def delete? request_method == :delete end - # Is this a HEAD request? request.method sees HEAD as :get, so check the - # HTTP method directly. + # Is this a HEAD request? <tt>request.method</tt> sees HEAD as <tt>:get</tt>, + # so check the HTTP method directly. def head? request_method == :head end diff --git a/actionpack/lib/action_controller/request_forgery_protection.rb b/actionpack/lib/action_controller/request_forgery_protection.rb index beb987f7ca..7e6961d25f 100644 --- a/actionpack/lib/action_controller/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/request_forgery_protection.rb @@ -102,7 +102,8 @@ module ActionController #:nodoc: request.format.html? || request.format.js? end - # Sets the token value for the current session. Pass a :secret option in #protect_from_forgery to add a custom salt to the hash. + # Sets the token value for the current session. Pass a <tt>:secret</tt> option + # in +protect_from_forgery+ to add a custom salt to the hash. def form_authenticity_token @form_authenticity_token ||= if request_forgery_protection_options[:secret] authenticity_token_from_session_id diff --git a/actionpack/lib/action_controller/rescue.rb b/actionpack/lib/action_controller/rescue.rb index d4d561bdb7..5022c9a815 100644 --- a/actionpack/lib/action_controller/rescue.rb +++ b/actionpack/lib/action_controller/rescue.rb @@ -58,33 +58,35 @@ module ActionController #:nodoc: # Rescue exceptions raised in controller actions. # # <tt>rescue_from</tt> receives a series of exception classes or class - # names, and a trailing :with option with the name of a method or a Proc - # object to be called to handle them. Alternatively a block can be given. + # names, and a trailing <tt>:with</tt> option with the name of a method + # or a Proc object to be called to handle them. Alternatively a block can + # be given. # # Handlers that take one argument will be called with the exception, so # that the exception can be inspected when dealing with it. # # Handlers are inherited. They are searched from right to left, from # bottom to top, and up the hierarchy. The handler of the first class for - # which exception.is_a?(klass) holds true is the one invoked, if any. + # which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if + # any. # - # class ApplicationController < ActionController::Base - # rescue_from User::NotAuthorized, :with => :deny_access # self defined exception - # rescue_from ActiveRecord::RecordInvalid, :with => :show_errors + # class ApplicationController < ActionController::Base + # rescue_from User::NotAuthorized, :with => :deny_access # self defined exception + # rescue_from ActiveRecord::RecordInvalid, :with => :show_errors # - # rescue_from 'MyAppError::Base' do |exception| - # render :xml => exception, :status => 500 - # end - # - # protected - # def deny_access - # ... + # rescue_from 'MyAppError::Base' do |exception| + # render :xml => exception, :status => 500 # end # - # def show_errors(exception) - # exception.record.new_record? ? ... - # end - # end + # protected + # def deny_access + # ... + # end + # + # def show_errors(exception) + # exception.record.new_record? ? ... + # end + # end def rescue_from(*klasses, &block) options = klasses.extract_options! unless options.has_key?(:with) @@ -165,7 +167,7 @@ module ActionController #:nodoc: # method if you wish to redefine the meaning of a local request to # include remote IP addresses or other criteria. def local_request? #:doc: - request.remote_addr == LOCALHOST and request.remote_ip == LOCALHOST + request.remote_addr == LOCALHOST && request.remote_ip == LOCALHOST end # Render detailed diagnostics for unhandled exceptions rescued from diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb index d3cedfdac7..0f0fa27d74 100644 --- a/actionpack/lib/action_controller/resources.rb +++ b/actionpack/lib/action_controller/resources.rb @@ -240,12 +240,12 @@ module ActionController # * <tt>:collection</tt> - add named routes for other actions that operate on the collection. # Takes a hash of <tt>#{action} => #{method}</tt>, where method is <tt>:get</tt>/<tt>:post</tt>/<tt>:put</tt>/<tt>:delete</tt> # or <tt>:any</tt> if the method does not matter. These routes map to a URL like /messages/rss, with a route of rss_messages_url. - # * <tt>:member</tt> - same as :collection, but for actions that operate on a specific member. - # * <tt>:new</tt> - same as :collection, but for actions that operate on the new resource action. + # * <tt>:member</tt> - same as <tt>:collection</tt>, but for actions that operate on a specific member. + # * <tt>:new</tt> - same as <tt>:collection</tt>, but for actions that operate on the new resource action. # * <tt>:controller</tt> - specify the controller name for the routes. # * <tt>:singular</tt> - specify the singular name used in the member routes. # * <tt>:requirements</tt> - set custom routing parameter requirements. - # * <tt>:conditions</tt> - specify custom routing recognition conditions. Resources sets the :method value for the method-specific routes. + # * <tt>:conditions</tt> - specify custom routing recognition conditions. Resources sets the <tt>:method</tt> value for the method-specific routes. # * <tt>:as</tt> - specify a different resource name to use in the URL path. For example: # # products_path == '/productos' # map.resources :products, :as => 'productos' do |product| @@ -254,7 +254,7 @@ module ActionController # end # # * <tt>:has_one</tt> - specify nested resources, this is a shorthand for mapping singleton resources beneath the current. - # * <tt>:has_many</tt> - same has :has_one, but for plural resources. + # * <tt>:has_many</tt> - same has <tt>:has_one</tt>, but for plural resources. # # You may directly specify the routing association with has_one and has_many like: # @@ -288,7 +288,7 @@ module ActionController # article.resources :comments # end # - # The comment resources work the same, but must now include a value for :article_id. + # The comment resources work the same, but must now include a value for <tt>:article_id</tt>. # # article_comments_url(@article) # article_comment_url(@article, @comment) @@ -302,7 +302,7 @@ module ActionController # map.resources :tags, :path_prefix => '/books/:book_id', :name_prefix => 'book_' # map.resources :tags, :path_prefix => '/toys/:toy_id', :name_prefix => 'toy_' # - # You may also use :name_prefix to override the generic named routes in a nested resource: + # You may also use <tt>:name_prefix</tt> to override the generic named routes in a nested resource: # # map.resources :articles do |article| # article.resources :comments, :name_prefix => nil @@ -364,7 +364,7 @@ module ActionController # # See map.resources for general conventions. These are the main differences: # * A singular name is given to map.resource. The default controller name is still taken from the plural name. - # * To specify a custom plural name, use the :plural option. There is no :singular option. + # * To specify a custom plural name, use the <tt>:plural</tt> option. There is no <tt>:singular</tt> option. # * No default index route is created for the singleton resource controller. # * When nesting singleton resources, only the singular name is used as the path prefix (example: 'account/messages/1') # diff --git a/actionpack/lib/action_controller/routing.rb b/actionpack/lib/action_controller/routing.rb index fa5a347db9..0bffe21431 100644 --- a/actionpack/lib/action_controller/routing.rb +++ b/actionpack/lib/action_controller/routing.rb @@ -23,7 +23,8 @@ module ActionController # map.connect ':controller/:action/:id' # # This route states that it expects requests to consist of a - # :controller followed by an :action that in turn is fed some :id. + # <tt>:controller</tt> followed by an <tt>:action</tt> that in turn is fed + # some <tt>:id</tt>. # # Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end up # with: @@ -36,11 +37,11 @@ module ActionController # Think of creating routes as drawing a map for your requests. The map tells # them where to go based on some predefined pattern: # - # ActionController::Routing::Routes.draw do |map| - # Pattern 1 tells some request to go to one place - # Pattern 2 tell them to go to another - # ... - # end + # ActionController::Routing::Routes.draw do |map| + # Pattern 1 tells some request to go to one place + # Pattern 2 tell them to go to another + # ... + # end # # The following symbols are special: # @@ -59,12 +60,12 @@ module ActionController # Within blocks, the empty pattern is at the highest priority. # In practice this works out nicely: # - # ActionController::Routing::Routes.draw do |map| - # map.with_options :controller => 'blog' do |blog| - # blog.show '', :action => 'list' - # end - # map.connect ':controller/:action/:view' - # end + # ActionController::Routing::Routes.draw do |map| + # map.with_options :controller => 'blog' do |blog| + # blog.show '', :action => 'list' + # end + # map.connect ':controller/:action/:view' + # end # # In this case, invoking blog controller (with an URL like '/blog/') # without parameters will activate the 'list' action by default. @@ -75,9 +76,10 @@ module ActionController # Hash at the end of your mapping to set any default parameters. # # Example: - # ActionController::Routing:Routes.draw do |map| - # map.connect ':controller/:action/:id', :controller => 'blog' - # end + # + # ActionController::Routing:Routes.draw do |map| + # map.connect ':controller/:action/:id', :controller => 'blog' + # end # # This sets up +blog+ as the default controller if no other is specified. # This means visiting '/' would invoke the blog controller. @@ -93,6 +95,7 @@ module ActionController # for the full URL and +name_of_route_path+ for the URI path. # # Example: + # # # In routes.rb # map.login 'login', :controller => 'accounts', :action => 'login' # @@ -138,22 +141,23 @@ module ActionController # # Routes can generate pretty URLs. For example: # - # map.connect 'articles/:year/:month/:day', - # :controller => 'articles', - # :action => 'find_by_date', - # :year => /\d{4}/, - # :month => /\d{1,2}/, - # :day => /\d{1,2}/ + # map.connect 'articles/:year/:month/:day', + # :controller => 'articles', + # :action => 'find_by_date', + # :year => /\d{4}/, + # :month => /\d{1,2}/, + # :day => /\d{1,2}/ + # + # Using the route above, the URL "http://localhost:3000/articles/2005/11/06" + # maps to # - # # Using the route above, the url below maps to: - # # params = {:year => '2005', :month => '11', :day => '06'} - # # http://localhost:3000/articles/2005/11/06 + # params = {:year => '2005', :month => '11', :day => '06'} # # == Regular Expressions and parameters # You can specify a regular expression to define a format for a parameter. # - # map.geocode 'geocode/:postalcode', :controller => 'geocode', - # :action => 'show', :postalcode => /\d{5}(-\d{4})?/ + # map.geocode 'geocode/:postalcode', :controller => 'geocode', + # :action => 'show', :postalcode => /\d{5}(-\d{4})?/ # # or, more formally: # @@ -182,7 +186,7 @@ module ActionController # # Specifying <tt>*[string]</tt> as part of a rule like: # - # map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?' + # map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?' # # will glob all remaining parts of the route that were not recognized earlier. This idiom # must appear at the end of the path. The globbed values are in <tt>params[:path]</tt> in @@ -210,7 +214,7 @@ module ActionController # # You can reload routes if you feel you must: # - # ActionController::Routing::Routes.reload + # ActionController::Routing::Routes.reload # # This will clear all named routes and reload routes.rb if the file has been modified from # last load. To absolutely force reloading, use +reload!+. @@ -221,19 +225,19 @@ module ActionController # # === +assert_routing+ # - # def test_movie_route_properly_splits - # opts = {:controller => "plugin", :action => "checkout", :id => "2"} - # assert_routing "plugin/checkout/2", opts - # end + # def test_movie_route_properly_splits + # opts = {:controller => "plugin", :action => "checkout", :id => "2"} + # assert_routing "plugin/checkout/2", opts + # end # # +assert_routing+ lets you test whether or not the route properly resolves into options. # # === +assert_recognizes+ # - # def test_route_has_options - # opts = {:controller => "plugin", :action => "show", :id => "12"} - # assert_recognizes opts, "/plugins/show/12" - # end + # def test_route_has_options + # opts = {:controller => "plugin", :action => "show", :id => "12"} + # assert_recognizes opts, "/plugins/show/12" + # end # # Note the subtle difference between the two: +assert_routing+ tests that # a URL fits options while +assert_recognizes+ tests that a URL @@ -241,16 +245,16 @@ module ActionController # # In tests you can simply pass the URL or named route to +get+ or +post+. # - # def send_to_jail - # get '/jail' - # assert_response :success - # assert_template "jail/front" - # end + # def send_to_jail + # get '/jail' + # assert_response :success + # assert_template "jail/front" + # end # - # def goes_to_login - # get login_url - # #... - # end + # def goes_to_login + # get login_url + # #... + # end # # == View a list of all your routes # diff --git a/actionpack/lib/action_controller/routing/builder.rb b/actionpack/lib/action_controller/routing/builder.rb index 50064055f4..b1a98d1a51 100644 --- a/actionpack/lib/action_controller/routing/builder.rb +++ b/actionpack/lib/action_controller/routing/builder.rb @@ -124,7 +124,7 @@ module ActionController route_requirements end - # Assign default options, such as 'index' as a default for :action. This + # Assign default options, such as 'index' as a default for <tt>:action</tt>. This # method must be run *after* user supplied requirements and defaults have # been applied to the segments. def assign_default_route_options(segments) @@ -187,7 +187,7 @@ module ActionController end # Routes cannot use the current string interpolation method - # if there are user-supplied :requirements as the interpolation + # if there are user-supplied <tt>:requirements</tt> as the interpolation # code won't raise RoutingErrors when generating if options.key?(:requirements) || route.requirements.keys.to_set != Routing::ALLOWED_REQUIREMENTS_FOR_OPTIMISATION route.optimise = false diff --git a/actionpack/lib/action_controller/routing/optimisations.rb b/actionpack/lib/action_controller/routing/optimisations.rb index ba4aeb4e82..3e3a2225f0 100644 --- a/actionpack/lib/action_controller/routing/optimisations.rb +++ b/actionpack/lib/action_controller/routing/optimisations.rb @@ -1,11 +1,11 @@ module ActionController module Routing # Much of the slow performance from routes comes from the - # complexity of expiry, :requirements matching, defaults providing + # complexity of expiry, <tt>:requirements</tt> matching, defaults providing # and figuring out which url pattern to use. With named routes # we can avoid the expense of finding the right route. So if # they've provided the right number of arguments, and have no - # :requirements, we can just build up a string and return it. + # <tt>:requirements</tt>, we can just build up a string and return it. # # To support building optimisations for other common cases, the # generation code is separated into several classes @@ -41,28 +41,29 @@ module ActionController end end - # Temporarily disabled :url optimisation pending proper solution to + # Temporarily disabled <tt>:url</tt> optimisation pending proper solution to # Issues around request.host etc. def applicable? true end end - # Given a route: - # map.person '/people/:id' + # Given a route # - # If the user calls person_url(@person), we can simply + # map.person '/people/:id' + # + # If the user calls <tt>person_url(@person)</tt>, we can simply # return a string like "/people/#{@person.to_param}" - # rather than triggering the expensive logic in url_for + # rather than triggering the expensive logic in +url_for+. class PositionalArguments < Optimiser def guard_condition number_of_arguments = route.segment_keys.size # if they're using foo_url(:id=>2) it's one # argument, but we don't want to generate /foos/id2 if number_of_arguments == 1 - "defined?(request) && request && args.size == 1 && !args.first.is_a?(Hash)" + "(!defined?(default_url_options) || default_url_options(nil).blank?) && defined?(request) && request && args.size == 1 && !args.first.is_a?(Hash)" else - "defined?(request) && request && args.size == #{number_of_arguments}" + "(!defined?(default_url_options) || default_url_options(nil).blank?) && defined?(request) && request && args.size == #{number_of_arguments}" end end @@ -77,7 +78,7 @@ module ActionController elements << '#{request.relative_url_root if request.relative_url_root}' - # The last entry in route.segments appears to # *always* be a + # The last entry in <tt>route.segments</tt> appears to *always* be a # 'divider segment' for '/' but we have assertions to ensure that # we don't include the trailing slashes, so skip them. (route.segments.size == 1 ? route.segments : route.segments[0..-2]).each do |segment| @@ -97,7 +98,7 @@ module ActionController # argument class PositionalArgumentsWithAdditionalParams < PositionalArguments def guard_condition - "defined?(request) && request && args.size == #{route.segment_keys.size + 1} && !args.last.has_key?(:anchor) && !args.last.has_key?(:port) && !args.last.has_key?(:host)" + "(!defined?(default_url_options) || default_url_options(nil).blank?) && defined?(request) && request && args.size == #{route.segment_keys.size + 1} && !args.last.has_key?(:anchor) && !args.last.has_key?(:port) && !args.last.has_key?(:host)" end # This case uses almost the same code as positional arguments, @@ -106,7 +107,7 @@ module ActionController super.insert(-2, '?#{args.last.to_query}') end - # To avoid generating http://localhost/?host=foo.example.com we + # To avoid generating "http://localhost/?host=foo.example.com" we # can't use this optimisation on routes without any segments def applicable? super && route.segment_keys.size > 0 diff --git a/actionpack/lib/action_controller/routing/route.rb b/actionpack/lib/action_controller/routing/route.rb index a83a599e35..a0d108ba03 100644 --- a/actionpack/lib/action_controller/routing/route.rb +++ b/actionpack/lib/action_controller/routing/route.rb @@ -139,8 +139,8 @@ module ActionController # those that were not used to generate a particular route. The extra # keys also do not include those recalled from the prior request, nor # do they include any keys that were implied in the route (like a - # :controller that is required, but not explicitly used in the text of - # the route.) + # <tt>:controller</tt> that is required, but not explicitly used in the + # text of the route.) def extra_keys(hash, recall={}) (hash || {}).keys.map { |k| k.to_sym } - (recall || {}).keys - significant_keys end diff --git a/actionpack/lib/action_controller/routing/route_set.rb b/actionpack/lib/action_controller/routing/route_set.rb index 6ba1a5c3ea..5bc13cf268 100644 --- a/actionpack/lib/action_controller/routing/route_set.rb +++ b/actionpack/lib/action_controller/routing/route_set.rb @@ -189,7 +189,7 @@ module ActionController end end - attr_accessor :routes, :named_routes + attr_accessor :routes, :named_routes, :configuration_file def initialize self.routes = [] @@ -238,8 +238,8 @@ module ActionController alias reload! load! def reload - if @routes_last_modified && defined?(RAILS_ROOT) - mtime = File.stat("#{RAILS_ROOT}/config/routes.rb").mtime + if @routes_last_modified && configuration_file + mtime = File.stat(configuration_file).mtime # if it hasn't been changed, then just return return if mtime == @routes_last_modified # if it has changed then record the new time and fall to the load! below @@ -249,9 +249,9 @@ module ActionController end def load_routes! - if defined?(RAILS_ROOT) && defined?(::ActionController::Routing::Routes) && self == ::ActionController::Routing::Routes - load File.join("#{RAILS_ROOT}/config/routes.rb") - @routes_last_modified = File.stat("#{RAILS_ROOT}/config/routes.rb").mtime + if configuration_file + load configuration_file + @routes_last_modified = File.stat(configuration_file).mtime else add_route ":controller/:action/:id" end diff --git a/actionpack/lib/action_controller/session/cookie_store.rb b/actionpack/lib/action_controller/session/cookie_store.rb index 5e5ef1bfb0..560491f996 100644 --- a/actionpack/lib/action_controller/session/cookie_store.rb +++ b/actionpack/lib/action_controller/session/cookie_store.rb @@ -14,27 +14,27 @@ require 'openssl' # to generate the HMAC message digest # TamperedWithCookie is raised if the data integrity check fails. # # A message digest is included with the cookie to ensure data integrity: -# a user cannot alter his user_id without knowing the secret key included in +# a user cannot alter his +user_id+ without knowing the secret key included in # the hash. New apps are generated with a pregenerated secret in # config/environment.rb. Set your own for old apps you're upgrading. # # Session options: -# :secret An application-wide key string or block returning a string -# called per generated digest. The block is called with the -# CGI::Session instance as an argument. It's important that the -# secret is not vulnerable to a dictionary attack. Therefore, -# you should choose a secret consisting of random numbers and -# letters and more than 30 characters. # -# Example: :secret => '449fe2e7daee471bffae2fd8dc02313d' -# :secret => Proc.new { User.current_user.secret_key } +# * <tt>:secret</tt>: An application-wide key string or block returning a string +# called per generated digest. The block is called with the CGI::Session +# instance as an argument. It's important that the secret is not vulnerable to +# a dictionary attack. Therefore, you should choose a secret consisting of +# random numbers and letters and more than 30 characters. Examples: # -# :digest The message digest algorithm used to verify session integrity -# defaults to 'SHA1' but may be any digest provided by OpenSSL, -# such as 'MD5', 'RIPEMD160', 'SHA256', etc. +# :secret => '449fe2e7daee471bffae2fd8dc02313d' +# :secret => Proc.new { User.current_user.secret_key } +# +# * <tt>:digest</tt>: The message digest algorithm used to verify session +# integrity defaults to 'SHA1' but may be any digest provided by OpenSSL, +# such as 'MD5', 'RIPEMD160', 'SHA256', etc. # # To generate a secret key for an existing application, run -# `rake secret` and set the key in config/environment.rb +# `rake secret` and set the key in config/environment.rb. # # Note that changing digest or secret invalidates all existing sessions! class CGI::Session::CookieStore diff --git a/actionpack/lib/action_controller/session_management.rb b/actionpack/lib/action_controller/session_management.rb index fabb6e7f60..8680104420 100644 --- a/actionpack/lib/action_controller/session_management.rb +++ b/actionpack/lib/action_controller/session_management.rb @@ -16,9 +16,11 @@ module ActionController #:nodoc: end module ClassMethods - # Set the session store to be used for keeping the session data between requests. By default, sessions are stored - # in browser cookies (:cookie_store), but you can also specify one of the other included stores - # (:active_record_store, :p_store, drb_store, :mem_cache_store, or :memory_store) or your own custom class. + # Set the session store to be used for keeping the session data between requests. + # By default, sessions are stored in browser cookies (<tt>:cookie_store</tt>), + # but you can also specify one of the other included stores (<tt>:active_record_store</tt>, + # <tt>:p_store</tt>, <tt>:drb_store</tt>, <tt>:mem_cache_store</tt>, or + # <tt>:memory_store</tt>) or your own custom class. def session_store=(store) ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:database_manager] = store.is_a?(Symbol) ? CGI::Session.const_get(store == :drb_store ? "DRbStore" : store.to_s.camelize) : store diff --git a/actionpack/lib/action_controller/streaming.rb b/actionpack/lib/action_controller/streaming.rb index b8e7ba2ac9..186e0e5531 100644 --- a/actionpack/lib/action_controller/streaming.rb +++ b/actionpack/lib/action_controller/streaming.rb @@ -17,24 +17,24 @@ module ActionController #:nodoc: # it feasible to send even large files. # # Be careful to sanitize the path parameter if it coming from a web - # page. send_file(params[:path]) allows a malicious user to + # page. <tt>send_file(params[:path])</tt> allows a malicious user to # download any file on your server. # # Options: # * <tt>:filename</tt> - suggests a filename for the browser to use. - # Defaults to File.basename(path). + # Defaults to <tt>File.basename(path)</tt>. # * <tt>:type</tt> - specifies an HTTP content type. # Defaults to 'application/octet-stream'. # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded. # Valid values are 'inline' and 'attachment' (default). - # * <tt>:stream</tt> - whether to send the file to the user agent as it is read (true) - # or to read the entire file before sending (false). Defaults to true. + # * <tt>:stream</tt> - whether to send the file to the user agent as it is read (+true+) + # or to read the entire file before sending (+false+). Defaults to +true+. # * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file. # Defaults to 4096. # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'. - # * <tt>:url_based_filename</tt> - set to true if you want the browser guess the filename from + # * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from # the URL, which is necessary for i18n filenames on certain browsers - # (setting :filename overrides this option). + # (setting <tt>:filename</tt> overrides this option). # # The default Content-Type and Content-Disposition headers are # set to download arbitrary binary files in as many browsers as @@ -42,17 +42,20 @@ module ActionController #:nodoc: # a variety of quirks (especially when downloading over SSL). # # Simple download: + # # send_file '/path/to.zip' # # Show a JPEG in the browser: + # # send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline' # # Show a 404 page in the browser: + # # send_file '/path/to/404.html', :type => 'text/html; charset=utf-8', :status => 404 # # Read about the other Content-* HTTP headers if you'd like to - # provide the user with more information (such as Content-Description). - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 + # provide the user with more information (such as Content-Description) in + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11. # # Also be aware that the document may be cached by proxies and browsers. # The Pragma and Cache-Control headers declare how the file may be cached @@ -95,7 +98,7 @@ module ActionController #:nodoc: # and specify whether to show data inline or download as an attachment. # # Options: - # * <tt>:filename</tt> - Suggests a filename for the browser to use. + # * <tt>:filename</tt> - suggests a filename for the browser to use. # * <tt>:type</tt> - specifies an HTTP content type. # Defaults to 'application/octet-stream'. # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded. @@ -103,12 +106,15 @@ module ActionController #:nodoc: # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'. # # Generic data download: + # # send_data buffer # # Download a dynamically-generated tarball: + # # send_data generate_tgz('dir'), :filename => 'dir.tgz' # # Display an image Active Record in the browser: + # # send_data image.data, :type => image.content_type, :disposition => 'inline' # # See +send_file+ for more information on HTTP Content-* headers and caching. diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 06b12a524f..77c6f26eac 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -16,9 +16,23 @@ module ActionController end class TestCase < ActiveSupport::TestCase + # When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline + # (bystepping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular + # rescue_action process takes place. This means you can test your rescue_action code by setting remote_addr to something else + # than 0.0.0.0. + # + # The exception is stored in the exception accessor for further inspection. module RaiseActionExceptions + attr_accessor :exception + def rescue_action(e) - raise e + self.exception = e + + if request.remote_addr == "0.0.0.0" + raise(e) + else + super(e) + end end end @@ -60,5 +74,10 @@ module ActionController @controller.request = @request = TestRequest.new @response = TestResponse.new end + + # Cause the action to be rescued according to the regular rules for rescue_action when the visitor is not local + def rescue_action_in_public! + @request.remote_addr = '208.77.188.166' # example.com + end end -end +end
\ No newline at end of file diff --git a/actionpack/lib/action_controller/test_process.rb b/actionpack/lib/action_controller/test_process.rb index f8af3ccaf2..dcb6cdf4ca 100644 --- a/actionpack/lib/action_controller/test_process.rb +++ b/actionpack/lib/action_controller/test_process.rb @@ -155,12 +155,12 @@ module ActionController #:nodoc: # A refactoring of TestResponse to allow the same behavior to be applied # to the "real" CgiResponse class in integration tests. module TestResponseBehavior #:nodoc: - # the response code of the request + # The response code of the request def response_code headers['Status'][0,3].to_i rescue 0 end - # returns a String to ensure compatibility with Net::HTTPResponse + # Returns a String to ensure compatibility with Net::HTTPResponse def code headers['Status'].to_s.split(' ')[0] end @@ -169,34 +169,34 @@ module ActionController #:nodoc: headers['Status'].to_s.split(' ',2)[1] end - # was the response successful? + # Was the response successful? def success? response_code == 200 end - # was the URL not found? + # Was the URL not found? def missing? response_code == 404 end - # were we redirected? + # Were we redirected? def redirect? (300..399).include?(response_code) end - # was there a server-side error? + # Was there a server-side error? def error? (500..599).include?(response_code) end alias_method :server_error?, :error? - # returns the redirection location or nil + # Returns the redirection location or nil def redirect_url headers['Location'] end - # does the redirect location match this regexp pattern? + # Does the redirect location match this regexp pattern? def redirect_url_match?( pattern ) return false if redirect_url.nil? p = Regexp.new(pattern) if pattern.class == String @@ -205,7 +205,7 @@ module ActionController #:nodoc: p.match(redirect_url) != nil end - # returns the template path of the file which was used to + # Returns the template path of the file which was used to # render this response (or nil) def rendered_file(with_controller=false) unless template.first_render.nil? @@ -217,50 +217,49 @@ module ActionController #:nodoc: end end - # was this template rendered by a file? + # Was this template rendered by a file? def rendered_with_file? !rendered_file.nil? end - # a shortcut to the flash (or an empty hash if no flash.. hey! that rhymes!) + # A shortcut to the flash. Returns an empyt hash if no session flash exists. def flash session['flash'] || {} end - # do we have a flash? + # Do we have a flash? def has_flash? !session['flash'].empty? end - # do we have a flash that has contents? + # Do we have a flash that has contents? def has_flash_with_contents? !flash.empty? end - # does the specified flash object exist? + # Does the specified flash object exist? def has_flash_object?(name=nil) !flash[name].nil? end - # does the specified object exist in the session? + # Does the specified object exist in the session? def has_session_object?(name=nil) !session[name].nil? end - # a shortcut to the template.assigns + # A shortcut to the template.assigns def template_objects template.assigns || {} end - # does the specified template object exist? + # Does the specified template object exist? def has_template_object?(name=nil) !template_objects[name].nil? end # Returns the response cookies, converted to a Hash of (name => CGI::Cookie) pairs - # Example: # - # assert_equal ['AuthorOfNewPage'], r.cookies['author'].value + # assert_equal ['AuthorOfNewPage'], r.cookies['author'].value def cookies headers['cookie'].inject({}) { |hash, cookie| hash[cookie.name] = cookie; hash } end @@ -465,10 +464,13 @@ module ActionController #:nodoc: return super end - # Shortcut for ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + path, type). Example: + # Shortcut for <tt>ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + path, type)</tt>: + # # post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png') # - # To upload binary files on Windows, pass :binary as the last parameter. This will not affect other platforms. + # To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter. + # This will not affect other platforms: + # # post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png', :binary) def fixture_file_upload(path, mime_type = nil, binary = false) ActionController::TestUploadedFile.new( @@ -483,17 +485,17 @@ module ActionController #:nodoc: # with a new RouteSet instance. # # The new instance is yielded to the passed block. Typically the block - # will create some routes using map.draw { map.connect ... }: + # will create some routes using <tt>map.draw { map.connect ... }</tt>: # - # with_routing do |set| - # set.draw do |map| - # map.connect ':controller/:action/:id' - # assert_equal( - # ['/content/10/show', {}], - # map.generate(:controller => 'content', :id => 10, :action => 'show') - # end - # end - # end + # with_routing do |set| + # set.draw do |map| + # map.connect ':controller/:action/:id' + # assert_equal( + # ['/content/10/show', {}], + # map.generate(:controller => 'content', :id => 10, :action => 'show') + # end + # end + # end # def with_routing real_routes = ActionController::Routing::Routes diff --git a/actionpack/lib/action_controller/url_rewriter.rb b/actionpack/lib/action_controller/url_rewriter.rb index 6f7e0cea09..b143806818 100644 --- a/actionpack/lib/action_controller/url_rewriter.rb +++ b/actionpack/lib/action_controller/url_rewriter.rb @@ -15,8 +15,8 @@ module ActionController # In addition to providing +url_for+, named routes are also accessible after # including UrlWriter. module UrlWriter - # The default options for urls written by this writer. Typically a :host pair - # is provided. + # The default options for urls written by this writer. Typically a <tt>:host</tt> + # pair is provided. mattr_accessor :default_url_options self.default_url_options = {} @@ -29,16 +29,19 @@ module ActionController # Generate a url based on the options provided, default_url_options and the # routes defined in routes.rb. The following options are supported: # - # * <tt>:only_path</tt> If true, the relative url is returned. Defaults to false. + # * <tt>:only_path</tt> If true, the relative url is returned. Defaults to +false+. # * <tt>:protocol</tt> The protocol to connect to. Defaults to 'http'. - # * <tt>:host</tt> Specifies the host the link should be targetted at. If <tt>:only_path</tt> is false, this option must be - # provided either explicitly, or via default_url_options. + # * <tt>:host</tt> Specifies the host the link should be targetted at. + # If <tt>:only_path</tt> is false, this option must be + # provided either explicitly, or via +default_url_options+. # * <tt>:port</tt> Optionally specify the port to connect to. # * <tt>:anchor</tt> An anchor name to be appended to the path. - # * <tt>:skip_relative_url_root</tt> If true, the url is not constructed using the relative_url_root set in <tt>ActionController::AbstractRequest.relative_url_root</tt>. + # * <tt>:skip_relative_url_root</tt> If true, the url is not constructed using the + # +relative_url_root+ set in ActionController::AbstractRequest.relative_url_root. # * <tt>:trailing_slash</tt> If true, adds a trailing slash, as in "/archive/2009/" # - # Any other key(:controller, :action, etc...) given to <tt>url_for</tt> is forwarded to the Routes module. + # Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to + # +url_for+ is forwarded to the Routes module. # # Examples: # |