diff options
author | rick <rick@spacemonkey.local> | 2008-05-05 23:19:21 -0700 |
---|---|---|
committer | rick <rick@spacemonkey.local> | 2008-05-05 23:19:21 -0700 |
commit | 0052938ac5b8894b27fdb9f27b1ed39f0a9ea176 (patch) | |
tree | f714643a4043d9fb73b39ec2a114d18f5deeffdd /actionpack/lib | |
parent | eacb5cf0cab6447db78085c8bda6c94dd329ce6b (diff) | |
parent | 3cffe92ff066c2b35eef409547db93652c5cccfc (diff) | |
download | rails-0052938ac5b8894b27fdb9f27b1ed39f0a9ea176.tar.gz rails-0052938ac5b8894b27fdb9f27b1ed39f0a9ea176.tar.bz2 rails-0052938ac5b8894b27fdb9f27b1ed39f0a9ea176.zip |
Merge commit 'core/master'
Diffstat (limited to 'actionpack/lib')
42 files changed, 433 insertions, 334 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: # diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 4ed20fec89..a6da81de07 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -242,18 +242,7 @@ If you are rendering a subtemplate, you must now use controller-like partial syn END_ERROR end - template = Template.new(self, template_path, use_full_path, local_assigns) - - begin - render_template(template) - rescue Exception => e - if TemplateError === e - e.sub_template_of(template.filename) - raise e - else - raise TemplateError.new(template, @assigns, e) - end - end + Template.new(self, template_path, use_full_path, local_assigns).render_template end # Renders the template present at <tt>template_path</tt> (relative to the view_paths array). @@ -290,7 +279,7 @@ If you are rendering a subtemplate, you must now use controller-like partial syn end def render_template(template) #:nodoc: - template.render + template.render_template end # Returns true is the file may be rendered implicitly. @@ -298,9 +287,10 @@ If you are rendering a subtemplate, you must now use controller-like partial syn template_path.split('/').last[0,1] != '_' end - # symbolized version of the :format parameter of the request, or :html by default. + # Returns a symbolized version of the <tt>:format</tt> parameter of the request, + # or <tt>:html</tt> by default. # - # EXCEPTION: If the :format parameter is not set, the Accept header will be examined for + # EXCEPTION: If the <tt>:format</tt> parameter is not set, the Accept header will be examined for # whether it contains the JavaScript mime type as its first priority. If that's the case, # it will be used. This ensures that Ajax applications can use the same URL to support both # JavaScript and non-JavaScript users. diff --git a/actionpack/lib/action_view/helpers/active_record_helper.rb b/actionpack/lib/action_view/helpers/active_record_helper.rb index 7569cc381d..f3f204cc97 100644 --- a/actionpack/lib/action_view/helpers/active_record_helper.rb +++ b/actionpack/lib/action_view/helpers/active_record_helper.rb @@ -8,47 +8,55 @@ module ActionView end module Helpers - # The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the form + # The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the +form+ # method that creates a complete form for all the basic content types of the record (not associations or aggregations, though). This # is a great way of making the record quickly available for editing, but likely to prove lackluster for a complicated real-world form. - # In that case, it's better to use the input method and the specialized form methods in link:classes/ActionView/Helpers/FormHelper.html + # In that case, it's better to use the +input+ method and the specialized +form+ methods in link:classes/ActionView/Helpers/FormHelper.html module ActiveRecordHelper - # Returns a default input tag for the type of object returned by the method. For example, let's say you have a model - # that has an attribute +title+ of type VARCHAR column, and this instance holds "Hello World": - # input("post", "title") => - # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> + # Returns a default input tag for the type of object returned by the method. For example, if <tt>@post</tt> + # has an attribute +title+ mapped to a +VARCHAR+ column that holds "Hello World": + # + # input("post", "title") + # # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> def input(record_name, method, options = {}) InstanceTag.new(record_name, method, self).to_tag(options) end - # Returns an entire form with all needed input tags for a specified Active Record object. For example, let's say you - # have a table model <tt>Post</tt> with attributes named <tt>title</tt> of type <tt>VARCHAR</tt> and <tt>body</tt> of type <tt>TEXT</tt>: + # Returns an entire form with all needed input tags for a specified Active Record object. For example, if <tt>@post</tt> + # has attributes named +title+ of type +VARCHAR+ and +body+ of type +TEXT+ then + # # form("post") - # That line would yield a form like the following: - # <form action='/post/create' method='post'> - # <p> - # <label for="post_title">Title</label><br /> - # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> - # </p> - # <p> - # <label for="post_body">Body</label><br /> - # <textarea cols="40" id="post_body" name="post[body]" rows="20"> - # </textarea> - # </p> - # <input type='submit' value='Create' /> - # </form> + # + # would yield a form like the following (modulus formatting): + # + # <form action='/posts/create' method='post'> + # <p> + # <label for="post_title">Title</label><br /> + # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> + # </p> + # <p> + # <label for="post_body">Body</label><br /> + # <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea> + # </p> + # <input name="commit" type="submit" value="Create" /> + # </form> # # It's possible to specialize the form builder by using a different action name and by supplying another - # block renderer. For example, let's say you have a model <tt>Entry</tt> with an attribute <tt>message</tt> of type <tt>VARCHAR</tt>: + # block renderer. For example, if <tt>@entry</tt> has an attribute +message+ of type +VARCHAR+ then + # + # form("entry", + # :action => "sign", + # :input_block => Proc.new { |record, column| + # "#{column.human_name}: #{input(record, column.name)}<br />" + # }) # - # form("entry", :action => "sign", :input_block => - # Proc.new { |record, column| "#{column.human_name}: #{input(record, column.name)}<br />" }) => + # would yield a form like the following (modulus formatting): # - # <form action='/post/sign' method='post'> - # Message: - # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /><br /> - # <input type='submit' value='Sign' /> - # </form> + # <form action="/entries/sign" method="post"> + # Message: + # <input id="entry_message" name="entry[message]" size="30" type="text" /><br /> + # <input name="commit" type="submit" value="Sign" /> + # </form> # # It's also possible to add additional content to the form by giving it a block, such as: # @@ -59,11 +67,11 @@ module ActionView # # The following options are available: # - # * <tt>action</tt> - the action used when submitting the form (default: create if a new record, otherwise update) - # * <tt>input_block</tt> - specialize the output using a different block, see above - # * <tt>method</tt> - the method used when submitting the form (default: post) - # * <tt>multipart</tt> - whether to change the enctype of the form to multipart/form-date, used when uploading a file (default: false) - # * <tt>submit_value</tt> - the text of the submit button (default: Create if a new record, otherwise Update) + # * <tt>:action</tt> - The action used when submitting the form (default: +create+ if a new record, otherwise +update+). + # * <tt>:input_block</tt> - Specialize the output using a different block, see above. + # * <tt>:method</tt> - The method used when submitting the form (default: +post+). + # * <tt>:multipart</tt> - Whether to change the enctype of the form to "multipart/form-data", used when uploading a file (default: +false+). + # * <tt>:submit_value</tt> - The text of the submit button (default: "Create" if a new record, otherwise "Update"). def form(record_name, options = {}) record = instance_variable_get("@#{record_name}") @@ -84,17 +92,16 @@ module ActionView # Returns a string containing the error message attached to the +method+ on the +object+ if one exists. # This error message is wrapped in a <tt>DIV</tt> tag, which can be extended to include a +prepend_text+ and/or +append_text+ # (to properly explain the error), and a +css_class+ to style it accordingly. +object+ should either be the name of an instance variable or - # the actual object. As an example, let's say you have a model - # +post+ that has an error message on the +title+ attribute: + # the actual object. As an example, let's say you have a model <tt>@post</tt> that has an error message on the +title+ attribute: # - # <%= error_message_on "post", "title" %> => - # <div class="formError">can't be empty</div> + # <%= error_message_on "post", "title" %> + # # => <div class="formError">can't be empty</div> # - # <%= error_message_on @post, "title" %> => - # <div class="formError">can't be empty</div> + # <%= error_message_on @post, "title" %> + # # => <div class="formError">can't be empty</div> # - # <%= error_message_on "post", "title", "Title simply ", " (or it won't work).", "inputError" %> => - # <div class="inputError">Title simply can't be empty (or it won't work).</div> + # <%= error_message_on "post", "title", "Title simply ", " (or it won't work).", "inputError" %> + # # => <div class="inputError">Title simply can't be empty (or it won't work).</div> def error_message_on(object, method, prepend_text = "", append_text = "", css_class = "formError") if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) && (errors = obj.errors.on(method)) @@ -110,30 +117,37 @@ module ActionView # # This <tt>DIV</tt> can be tailored by the following options: # - # * <tt>header_tag</tt> - Used for the header of the error div (default: h2) - # * <tt>id</tt> - The id of the error div (default: errorExplanation) - # * <tt>class</tt> - The class of the error div (default: errorExplanation) - # * <tt>object</tt> - The object (or array of objects) for which to display errors, if you need to escape the instance variable convention - # * <tt>object_name</tt> - The object name to use in the header, or any text that you prefer. If <tt>object_name</tt> is not set, the name of the first object will be used. - # * <tt>header_message</tt> - The message in the header of the error div. Pass +nil+ or an empty string to avoid the header message altogether. (default: X errors prohibited this object from being saved) - # * <tt>message</tt> - The explanation message after the header message and before the error list. Pass +nil+ or an empty string to avoid the explanation message altogether. (default: There were problems with the following fields:) + # * <tt>:header_tag</tt> - Used for the header of the error div (default: "h2"). + # * <tt>:id</tt> - The id of the error div (default: "errorExplanation"). + # * <tt>:class</tt> - The class of the error div (default: "errorExplanation"). + # * <tt>:object</tt> - The object (or array of objects) for which to display errors, + # if you need to escape the instance variable convention. + # * <tt>:object_name</tt> - The object name to use in the header, or any text that you prefer. + # If <tt>:object_name</tt> is not set, the name of the first object will be used. + # * <tt>:header_message</tt> - The message in the header of the error div. Pass +nil+ + # or an empty string to avoid the header message altogether. (Default: "X errors + # prohibited this object from being saved"). + # * <tt>:message</tt> - The explanation message after the header message and before + # the error list. Pass +nil+ or an empty string to avoid the explanation message + # altogether. (Default: "There were problems with the following fields:"). # - # To specify the display for one object, you simply provide its name as a parameter. For example, for the +User+ model: + # To specify the display for one object, you simply provide its name as a parameter. + # For example, for the <tt>@user</tt> model: # # error_messages_for 'user' # - # To specify more than one object, you simply list them; optionally, you can add an extra +object_name+ parameter, which - # will be the name used in the header message. + # To specify more than one object, you simply list them; optionally, you can add an extra <tt>:object_name</tt> parameter, which + # will be the name used in the header message: # # error_messages_for 'user_common', 'user', :object_name => 'user' # - # If the objects cannot be located as instance variables, you can add an extra +object+ paremeter which gives the actual - # object (or array of objects to use) + # If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> paremeter which gives the actual + # object (or array of objects to use): # # error_messages_for 'user', :object => @question.user # # NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what - # you need is significantly different from the default presentation, it makes plenty of sense to access the object.errors + # you need is significantly different from the default presentation, it makes plenty of sense to access the <tt>object.errors</tt> # instance yourself and set it up. View the source of this method to see how easy it is. def error_messages_for(*params) options = params.extract_options!.symbolize_keys diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb index 0cce96b184..dfc7e2b3ed 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb @@ -164,7 +164,7 @@ module ActionView # current page or you can pass the full path relative to your document # root. To include the Prototype and Scriptaculous javascript libraries in # your application, pass <tt>:defaults</tt> as the source. When using - # :defaults, if an <tt>application.js</tt> file exists in your public + # <tt>:defaults</tt>, if an application.js file exists in your public # javascripts directory, it will be included as well. You can modify the # html attributes of the script tag by passing a hash as the last argument. # @@ -332,7 +332,7 @@ module ActionView # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" /> # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" /> # - # You can also include all styles in the stylesheet directory using :all as the source: + # You can also include all styles in the stylesheet directory using <tt>:all</tt> as the source: # # stylesheet_link_tag :all # => # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" /> diff --git a/actionpack/lib/action_view/helpers/benchmark_helper.rb b/actionpack/lib/action_view/helpers/benchmark_helper.rb index fefa28f4d7..743d1d40ec 100644 --- a/actionpack/lib/action_view/helpers/benchmark_helper.rb +++ b/actionpack/lib/action_view/helpers/benchmark_helper.rb @@ -21,11 +21,13 @@ module ActionView # You may give an optional logger level as the second argument # (:debug, :info, :warn, :error); the default value is :info. def benchmark(message = "Benchmarking", level = :info) - if @logger + if controller.logger real = Benchmark.realtime { yield } - @logger.send level, "#{message} (#{'%.5f' % real})" + controller.logger.send(level, "#{message} (#{'%.5f' % real})") + else + yield end end end end -end +end
\ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 9f7790d0f9..cbd390421a 100755 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -104,17 +104,17 @@ module ActionView # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute (identified by # +method+) on an object assigned to the template (identified by +object+). It's possible to tailor the selects through the +options+ hash, - # which accepts all the keys that each of the individual select builders do (like :use_month_numbers for select_month) as well as a range of + # which accepts all the keys that each of the individual select builders do (like <tt>:use_month_numbers</tt> for select_month) as well as a range of # discard options. The discard options are <tt>:discard_year</tt>, <tt>:discard_month</tt> and <tt>:discard_day</tt>. Set to true, they'll # drop the respective select. Discarding the month select will also automatically discard the day select. It's also possible to explicitly # set the order of the tags using the <tt>:order</tt> option with an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in # the desired order. Symbols may be omitted and the respective select is not included. # - # Pass the <tt>:default</tt> option to set the default date. Use a Time object or a Hash of :year, :month, :day, :hour, :minute, and :second. + # Pass the <tt>:default</tt> option to set the default date. Use a Time object or a Hash of <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt>, and <tt>:second</tt>. # - # Passing :disabled => true as part of the +options+ will make elements inaccessible for change. + # Passing <tt>:disabled => true</tt> as part of the +options+ will make elements inaccessible for change. # - # If anything is passed in the html_options hash it will be applied to every select tag in the set. + # If anything is passed in the +html_options+ hash it will be applied to every select tag in the set. # # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. # diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index 0e77a7e067..63c5fd57aa 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -1,6 +1,7 @@ require 'cgi' require 'action_view/helpers/date_helper' require 'action_view/helpers/tag_helper' +require 'action_view/helpers/form_tag_helper' module ActionView module Helpers @@ -51,7 +52,7 @@ module ActionView # # If the object name contains square brackets the id for the object will be inserted. For example: # - # <%= text_field "person[]", "name" %> + # <%= text_field "person[]", "name" %> # # ...will generate the following ERb. # @@ -91,7 +92,7 @@ module ActionView # # Even further, the form_for method allows you to more easily escape the instance variable convention. So while the stand-alone # approach would require <tt>text_field :person, :name, :object => person</tt> - # to work with local variables instead of instance ones, the form_for calls remain the same. You simply declare once with + # to work with local variables instead of instance ones, the form_for calls remain the same. You simply declare once with # <tt>:person, person</tt> and all subsequent field calls save <tt>:person</tt> and <tt>:object => person</tt>. # # Also note that form_for doesn't create an exclusive scope. It's still possible to use both the stand-alone FormHelper methods @@ -107,7 +108,7 @@ module ActionView # 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. # - # HTML attributes for the form tag can be given as :html => {...}. For example: + # HTML attributes for the form tag can be given as <tt>:html => {...}</tt>. For example: # # <% form_for :person, @person, :html => {:id => 'person_form'} do |f| %> # ... @@ -149,7 +150,7 @@ module ActionView # ... # <% end %> # - # And for namespaced routes, like admin_post_url: + # And for namespaced routes, like admin_post_url: # # <% form_for([:admin, @post]) do |f| %> # ... @@ -337,7 +338,7 @@ module ActionView # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example # shown. # - # ==== Examples + # ==== Examples # hidden_field(:signup, :pass_confirm) # # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" /> # @@ -404,7 +405,7 @@ module ActionView # is set to 0 which is convenient for boolean values. Since HTTP standards say that unchecked checkboxes don't post anything, # we add a hidden value with the same name as the checkbox as a work around. # - # ==== Examples + # ==== Examples # # Let's say that @post.validated? is 1: # check_box("post", "validated") # # => <input type="checkbox" id="post_validated" name="post[validated]" value="1" /> @@ -445,7 +446,7 @@ module ActionView end class InstanceTag #:nodoc: - include Helpers::TagHelper + include Helpers::TagHelper, Helpers::FormTagHelper attr_reader :method_name, :object_name @@ -467,11 +468,13 @@ module ActionView end def to_label_tag(text = nil, options = {}) + options = options.stringify_keys name_and_id = options.dup add_default_name_and_id(name_and_id) - options["for"] = name_and_id["id"] + options.delete("index") + options["for"] ||= name_and_id["id"] content = (text.blank? ? nil : text.to_s) || method_name.humanize - content_tag("label", content, options) + label_tag(name_and_id["id"], content, options) end def to_input_field_tag(field_type, options = {}) @@ -483,6 +486,7 @@ module ActionView end options["type"] = field_type options["value"] ||= value_before_type_cast(object) unless field_type == "file" + options["value"] &&= html_escape(options["value"]) add_default_name_and_id(options) tag("input", options) end diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 5b026245da..bf65fe5574 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -93,8 +93,8 @@ module ActionView # This allows the user to submit a form page more than once with the expected results of creating multiple records. # In addition, this allows a single partial to be used to generate form inputs for both edit and create forms. # - # By default, post.person_id is the selected option. Specify :selected => value to use a different selection - # or :selected => nil to leave all options unselected. + # 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. def select(object, method, choices, options = {}, html_options = {}) InstanceTag.new(object, method, self, nil, options.delete(:object)).to_select_tag(choices, options, 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 0544ed3ded..f37b428b80 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -341,8 +341,9 @@ module ActionView # submit_tag nil, :class => "form_submit" # # => <input class="form_submit" name="commit" type="submit" /> # - # submit_tag "Edit", :disable_with => "Editing...", :class => 'edit-button' - # # => <input class="edit-button" disable_with="Editing..." name="commit" type="submit" value="Edit" /> + # submit_tag "Edit", :disable_with => "Editing...", :class => "edit-button" + # # => <input class="edit-button" onclick="this.disabled=true;this.value='Editing...';this.form.submit();" + # # name="commit" type="submit" value="Edit" /> def submit_tag(value = "Save changes", options = {}) options.stringify_keys! diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb index 81938ac8e3..908728c0e6 100644 --- a/actionpack/lib/action_view/helpers/prototype_helper.rb +++ b/actionpack/lib/action_view/helpers/prototype_helper.rb @@ -255,10 +255,10 @@ module ActionView link_to_function(name, remote_function(options), html_options || options.delete(:html)) end - # Periodically calls the specified url (<tt>options[:url]</tt>) every + # Periodically calls the specified url (<tt>options[:url]</tt>) every # <tt>options[:frequency]</tt> seconds (default is 10). Usually used to - # update a specified div (<tt>options[:update]</tt>) with the results - # of the remote call. The options for specifying the target with :url + # update a specified div (<tt>options[:update]</tt>) with the results + # of the remote call. The options for specifying the target with <tt>:url</tt> # and defining callbacks is the same as link_to_remote. # Examples: # # Call get_averages and put its results in 'avg' every 10 seconds @@ -291,11 +291,11 @@ module ActionView # though it's using JavaScript to serialize the form elements, the form # submission will work just like a regular submission as viewed by the # receiving side (all elements available in <tt>params</tt>). The options for - # specifying the target with :url and defining callbacks is the same as - # link_to_remote. + # specifying the target with <tt>:url</tt> and defining callbacks is the same as + # +link_to_remote+. # # A "fall-through" target for browsers that doesn't do JavaScript can be - # specified with the :action/:method options on :html. + # specified with the <tt>:action</tt>/<tt>:method</tt> options on <tt>:html</tt>. # # Example: # # Generates: @@ -304,11 +304,11 @@ module ActionView # form_remote_tag :html => { :action => # url_for(:controller => "some", :action => "place") } # - # The Hash passed to the :html key is equivalent to the options (2nd) + # The Hash passed to the <tt>:html</tt> key is equivalent to the options (2nd) # argument in the FormTagHelper.form_tag method. # # By default the fall-through action is the same as the one specified in - # the :url (and the default method is :post). + # the <tt>:url</tt> (and the default method is <tt>:post</tt>). # # form_remote_tag also takes a block, like form_tag: # # Generates: @@ -422,8 +422,8 @@ module ActionView end # Returns '<tt>eval(request.responseText)</tt>' which is the JavaScript function - # that form_remote_tag can call in :complete to evaluate a multiple - # update return document using update_element_function calls. + # that +form_remote_tag+ can call in <tt>:complete</tt> to evaluate a multiple + # update return document using +update_element_function+ calls. def evaluate_remote_response "eval(request.responseText)" end diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb index 47fbe3a27a..3129ff414e 100644 --- a/actionpack/lib/action_view/helpers/sanitize_helper.rb +++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb @@ -10,7 +10,7 @@ module ActionView base.extend(ClassMethods) end - # This #sanitize helper will html encode all tags and strip all attributes that aren't specifically allowed. + # This +sanitize+ helper will html encode all tags and strip all attributes that aren't specifically allowed. # It also strips href/src tags with invalid protocols, like javascript: especially. It does its best to counter any # tricks that hackers may use, like throwing in unicode/ascii/hex values to get past the javascript: filters. Check out # the extensive test suite. @@ -18,7 +18,7 @@ module ActionView # <%= sanitize @article.body %> # # You can add or remove tags/attributes if you want to customize it a bit. See ActionView::Base for full docs on the - # available options. You can add tags/attributes for single uses of #sanitize by passing either the :attributes or :tags options: + # available options. You can add tags/attributes for single uses of +sanitize+ by passing either the <tt>:attributes</tt> or <tt>:tags</tt> options: # # Normal Use # diff --git a/actionpack/lib/action_view/helpers/scriptaculous_helper.rb b/actionpack/lib/action_view/helpers/scriptaculous_helper.rb index 60e285b722..12b4cfd3f8 100644 --- a/actionpack/lib/action_view/helpers/scriptaculous_helper.rb +++ b/actionpack/lib/action_view/helpers/scriptaculous_helper.rb @@ -35,8 +35,8 @@ module ActionView # This would fade the element that was dropped on the drop receiving # element. # - # For toggling visual effects, you can use :toggle_appear, :toggle_slide, and - # :toggle_blind which will alternate between appear/fade, slidedown/slideup, and + # For toggling visual effects, you can use <tt>:toggle_appear</tt>, <tt>:toggle_slide</tt>, and + # <tt>:toggle_blind</tt> which will alternate between appear/fade, slidedown/slideup, and # blinddown/blindup respectively. # # You can change the behaviour with various options, see diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 4a951f2c88..6d27494213 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -16,7 +16,7 @@ module ActionView # instead of the fully qualified URL like http://example.com/controller/action. # # When called from a view, url_for returns an HTML escaped url. If you - # need an unescaped url, pass :escape => false in the +options+. + # need an unescaped url, pass <tt>:escape => false</tt> in the +options+. # # ==== Options # * <tt>:anchor</tt> -- specifies the anchor name to be appended to the path. @@ -25,8 +25,8 @@ module ActionView # is currently not recommended since it breaks caching. # * <tt>:host</tt> -- overrides the default (current) host if provided # * <tt>:protocol</tt> -- overrides the default (current) protocol if provided - # * <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>:escape</tt> -- Determines whether the returned URL will be HTML escaped or not (<tt>true</tt> by default) # # ==== Relying on named routes @@ -102,21 +102,21 @@ module ActionView # create an HTML form and immediately submit the form for processing using # the HTTP verb specified. Useful for having links perform a POST operation # in dangerous actions like deleting a record (which search bots can follow - # while spidering your site). Supported verbs are :post, :delete and :put. + # while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>. # Note that if the user has JavaScript disabled, the request will fall back # to using GET. If you are relying on the POST behavior, you should check # for it in your controller's action by using the request object's methods - # for post?, delete? or put?. + # for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>. # * The +html_options+ will accept a hash of html attributes for the link tag. # # Note that if the user has JavaScript disabled, the request will fall back - # to using GET. If :href=>'#' is used and the user has JavaScript disabled + # to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript disabled # clicking the link will have no effect. If you are relying on the POST # behavior, your should check for it in your controller's action by using the - # request object's methods for post?, delete? or put?. + # request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>. # # You can mix and match the +html_options+ with the exception of - # :popup and :method which will raise an ActionView::ActionViewError + # <tt>:popup</tt> and <tt>:method</tt> which will raise an ActionView::ActionViewError # exception. # # ==== Examples diff --git a/actionpack/lib/action_view/partial_template.rb b/actionpack/lib/action_view/partial_template.rb index 7d9c59a41c..1fb3aaee02 100644 --- a/actionpack/lib/action_view/partial_template.rb +++ b/actionpack/lib/action_view/partial_template.rb @@ -24,10 +24,12 @@ module ActionView #:nodoc: def render_member(object) @locals[@counter_name] += 1 @locals[:object] = @locals[@variable_name] = object - returning render do - @locals.delete(@variable_name) - @locals.delete(:object) - end + + template = render_template + @locals.delete(@variable_name) + @locals.delete(:object) + + template end def counter=(num) diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb index 37b717d848..a708ecb3fb 100644 --- a/actionpack/lib/action_view/partials.rb +++ b/actionpack/lib/action_view/partials.rb @@ -100,18 +100,18 @@ module ActionView # Title: <%= chief.name %> # </div> # - # As you can see, the :locals hash is shared between both the partial and its layout. + # As you can see, the <tt>:locals</tt> hash is shared between both the partial and its layout. module Partials private def render_partial(partial_path, object_assigns = nil, local_assigns = {}) #:nodoc: case partial_path when String, Symbol, NilClass # Render the template - ActionView::PartialTemplate.new(self, partial_path, object_assigns, local_assigns).render + ActionView::PartialTemplate.new(self, partial_path, object_assigns, local_assigns).render_template when ActionView::Helpers::FormBuilder builder_partial_path = partial_path.class.to_s.demodulize.underscore.sub(/_builder$/, '') render_partial(builder_partial_path, object_assigns, (local_assigns || {}).merge(builder_partial_path.to_sym => partial_path)) - when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::Associations::HasManyThroughAssociation + when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope if partial_path.any? collection = partial_path render_partial_collection(nil, collection, nil, local_assigns) diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index bc3d8d5e52..2cda3d94b5 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -17,6 +17,18 @@ module ActionView #:nodoc: @locals = locals || {} @handler = self.class.handler_class_for_extension(@extension).new(@view) end + + def render_template + render + rescue Exception => e + raise e unless filename + if TemplateError === e + e.sub_template_of(filename) + raise e + else + raise TemplateError.new(self, @view.assigns, e) + end + end def render prepare! diff --git a/actionpack/lib/action_view/template_finder.rb b/actionpack/lib/action_view/template_finder.rb index aaf34de538..83b7e27c09 100644 --- a/actionpack/lib/action_view/template_finder.rb +++ b/actionpack/lib/action_view/template_finder.rb @@ -24,7 +24,12 @@ module ActionView #:nodoc: view_paths.flatten.compact.each do |dir| next if @@processed_view_paths.has_key?(dir) @@processed_view_paths[dir] = [] - Dir.glob("#{dir}/**/*/**").each do |file| + + # + # Dir.glob("#{dir}/**/*/**") reads all the directories in view path and templates inside those directories + # Dir.glob("#{dir}/**") reads templates residing at top level of view path + # + (Dir.glob("#{dir}/**/*/**") | Dir.glob("#{dir}/**")).each do |file| unless File.directory?(file) @@processed_view_paths[dir] << file.split(dir).last.sub(/^\//, '') diff --git a/actionpack/lib/action_view/template_handlers/builder.rb b/actionpack/lib/action_view/template_handlers/builder.rb index cff9e6beb8..f76d89777a 100644 --- a/actionpack/lib/action_view/template_handlers/builder.rb +++ b/actionpack/lib/action_view/template_handlers/builder.rb @@ -13,7 +13,7 @@ module ActionView content_type_handler = (@view.send!(:controller).respond_to?(:response) ? "controller.response" : "controller") "#{content_type_handler}.content_type ||= Mime::XML\n" + "xml = ::Builder::XmlMarkup.new(:indent => 2)\n" + - template + + template.source + "\nxml.target!\n" end diff --git a/actionpack/lib/action_view/template_handlers/compilable.rb b/actionpack/lib/action_view/template_handlers/compilable.rb index 35c74f6c51..25bd0fea7f 100644 --- a/actionpack/lib/action_view/template_handlers/compilable.rb +++ b/actionpack/lib/action_view/template_handlers/compilable.rb @@ -95,7 +95,7 @@ module ActionView # Method to create the source code for a given template. def create_template_source(template, render_symbol) - body = compile(template.source) + body = compile(template) self.template_args[render_symbol] ||= {} locals_keys = self.template_args[render_symbol].keys | template.locals.keys diff --git a/actionpack/lib/action_view/template_handlers/erb.rb b/actionpack/lib/action_view/template_handlers/erb.rb index f30cf0203c..15a9064461 100644 --- a/actionpack/lib/action_view/template_handlers/erb.rb +++ b/actionpack/lib/action_view/template_handlers/erb.rb @@ -43,7 +43,7 @@ module ActionView include Compilable def compile(template) - ::ERB.new(template, nil, @view.erb_trim_mode).src + ::ERB.new(template.source, nil, @view.erb_trim_mode).src end def cache_fragment(block, name = {}, options = nil) #:nodoc: diff --git a/actionpack/lib/action_view/template_handlers/rjs.rb b/actionpack/lib/action_view/template_handlers/rjs.rb index e0f95205de..5854e33fed 100644 --- a/actionpack/lib/action_view/template_handlers/rjs.rb +++ b/actionpack/lib/action_view/template_handlers/rjs.rb @@ -9,7 +9,7 @@ module ActionView def compile(template) "controller.response.content_type ||= Mime::JS\n" + - "update_page do |page|\n#{template}\nend" + "update_page do |page|\n#{template.source}\nend" end def cache_fragment(block, name = {}, options = nil) #:nodoc: |