From 03bb1ebec513de779908af110c46e16b9c882673 Mon Sep 17 00:00:00 2001
From: Pratik Naik <pratiknaik@gmail.com>
Date: Wed, 4 Feb 2009 01:44:58 +0000
Subject: Convert the guides from asciidoc to textile and integrate with the
 new design.

If you're a guide writer and want to generate the guides, Run :

  ruby railties/guides/rails_guides.rb

And guides HTML will get generated inside railties/guides/output directory.
---
 .../source/action_controller_overview.textile      | 798 +++++++++++++++++++++
 1 file changed, 798 insertions(+)
 create mode 100644 railties/guides/source/action_controller_overview.textile

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
new file mode 100644
index 0000000000..d51f2a9745
--- /dev/null
+++ b/railties/guides/source/action_controller_overview.textile
@@ -0,0 +1,798 @@
+h2. Action Controller Overview
+
+In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:
+
+* Follow the flow of a request through a controller
+* Understand why and how to store data in the session or cookies
+* Work with filters to execute code during request processing
+* Use Action Controller's built-in HTTP authentication
+* Stream data directly to the user's browser
+* Filter sensitive parameters so they do not appear in the application's log
+* Deal with exceptions that may be raised during request processing
+
+endprologue.
+
+h3. What Does a Controller do?
+
+Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.
+
+For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
+
+A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
+
+NOTE: For more details on the routing process, see "Rails Routing from the Outside In":routing_outside_in.html.
+
+h3. Methods and Actions
+
+A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.
+
+<ruby>
+class ClientsController < ApplicationController
+
+  # Actions are public methods
+  def new
+  end
+
+  # Action methods are responsible for producing output
+  def edit
+  end
+
+# Helper methods are private and can not be used as actions
+private
+
+  def foo
+  end
+
+end
+</ruby>
+
+There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.
+
+As an example, if a user goes to +/clients/new+ in your application to add a new client, Rails will create an instance of ClientsController and run the +new+ method. Note that the empty method from the example above could work just fine because Rails will by default render the +new.html.erb+ view unless the action says otherwise. The +new+ method could make available to the view a +@client+ instance variable by creating a new Client:
+
+<ruby>
+def new
+  @client = Client.new
+end
+</ruby>
+
+The "Layouts & rendering guide":layouts_and_rendering.html explains this in more detail.
+
+ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
+
+
+h3. Parameters
+
+You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the +params+ hash in your controller:
+
+<ruby>
+class ClientsController < ActionController::Base
+
+  # This action uses query string parameters because it gets run by a HTTP 
+  # GET request, but this does not make any difference to the way in which 
+  # the parameters are accessed. The URL for this action would look like this 
+  # in order to list activated clients: /clients?status=activated
+  def index
+    if params[:status] = "activated"
+      @clients = Client.activated
+    else
+      @clients = Client.unativated
+    end
+  end
+
+  # This action uses POST parameters. They are most likely coming from an HTML
+  # form which the user has submitted. The URL for this RESTful request will
+  # be "/clients", and the data will be sent as part of the request body.
+  def create
+    @client = Client.new(params[:client])
+    if @client.save
+      redirect_to @client
+    else
+      # This line overrides the default rendering behavior, which would have been
+      # to render the "create" view.
+      render :action => "new"
+    end
+  end
+
+end
+</ruby>
+
+h4. Hash and Array Parameters
+
+The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:
+
+<pre><code>
+GET /clients?ids[]=1&ids[]=2&ids[]=3
+</code></pre>
+
+NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
+
+The value of +params[:ids]+ will now be +["1", "2", "3"]+. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
+
+To send a hash you include the key name inside the brackets:
+
+<html>
+<form action="/clients" method="post">
+  <input type="text" name="client[name]" value="Acme" />
+  <input type="text" name="client[phone]" value="12345" />
+  <input type="text" name="client[address][postcode]" value="12345" />
+  <input type="text" name="client[address][city]" value="Carrot City" />
+</form>
+</html>
+
+The value of +params[:client]+ when this form is submitted  will be +{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}+. Note the nested hash in +params[:client][:address]+.
+
+Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.
+
+h4. Routing Parameters
+
+The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL:
+
+<ruby>
+# ...
+map.connect "/clients/:status", :controller => "clients", :action => "index", :foo => "bar"
+# ...
+</ruby>
+
+In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string in the same way +params[:action]+ will contain "index".
+
+h4. default_url_options
+
+You can set global default parameters that will be used when generating URLs with +default_url_options+. To do this, define a method with that name in your controller:
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+  #The options parameter is the hash passed in to +url_for+
+  def default_url_options(options)
+    {:locale => I18n.locale}
+  end
+
+end
+</ruby>
+
+These options will be used as a starting-point when generating, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
+
+
+h3. Session
+
+Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
+
+* CookieStore - Stores everything on the client.
+* DRbStore - Stores the data on a DRb server.
+* MemCacheStore - Stores the data in a memcache.
+* ActiveRecordStore - Stores the data in a database using Active Record.
+
+All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL).
+
+Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The CookieStore has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
+
+Read more about session storage in the "Security Guide":security.html.
+
+If you need a different session storage mechanism, you can change it in the +config/environment.rb+ file:
+
+<ruby>
+# Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]
+config.action_controller.session_store = :active_record_store
+</ruby>
+
+h4. Accessing the Session
+
+In your controller you can access the session through the +session+ instance method.
+
+NOTE: Sessions are lazily loaded. If you don't access sessions in your action's code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.
+
+Session values are stored using key/value pairs like a hash:
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+private
+
+  # Finds the User with the ID stored in the session with the key :current_user_id
+  # This is a common way to handle user login in a Rails application; logging in sets the
+  # session value and logging out removes it.
+  def current_user
+    @_current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
+  end
+
+end
+</ruby>
+
+To store something in the session, just assign it to the key like a hash:
+
+<ruby>
+class LoginsController < ApplicationController
+
+  # "Create" a login, aka "log the user in"
+  def create
+    if user = User.authenticate(params[:username, params[:password])
+      # Save the user ID in the session so it can be used in subsequent requests
+      session[:current_user_id] = user.id
+      redirect_to root_url
+    end
+  end
+
+end
+</ruby>
+
+To remove something from the session, assign that key to be +nil+:
+
+<ruby>
+class LoginsController < ApplicationController
+
+  # "Delete" a login, aka "log the user out"
+  def destroy
+    # Remove the user id from the session
+    session[:current_user_id] = nil
+    redirect_to root_url
+  end
+
+end
+</ruby>
+
+To reset the entire session, use +reset_session+.
+
+h4. The flash
+
+The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
+
+<ruby>
+class LoginsController < ApplicationController
+
+  def destroy
+    session[:current_user_id] = nil
+    flash[:notice] = "You have successfully logged out"
+    redirect_to root_url
+  end
+
+end
+</ruby>
+
+The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
+
+<ruby>
+<html>
+  <!-- <head/> -->
+  <body>
+    <% if flash[:notice] -%>
+      <p class="notice"><%= flash[:notice] %></p>
+    <% end -%>
+    <% if flash[:error] -%>
+      <p class="error"><%= flash[:error] %></p>
+    <% end -%>
+    <!-- more content -->
+  </body>
+</html>
+</ruby>
+
+This way, if an action sets an error or a notice message, the layout will display it automatically.
+
+If you want a flash value to be carried over to another request, use the +keep+ method:
+
+<ruby>
+class MainController < ApplicationController
+
+  # Let's say this action corresponds to root_url, but you want all requests here to be redirected to
+  # UsersController#index. If an action sets the flash and redirects here, the values would normally be
+  # lost when another redirect happens, but you can use keep to make it persist for another request.
+  def index
+    flash.keep # Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice)
+    redirect_to users_url
+  end
+
+end
+</ruby>
+
+h5. flash.now
+
+By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the +create+ action fails to save a resource and you render the +new+ template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use +flash.now+ in the same way you use the normal +flash+:
+
+<ruby>
+class ClientsController < ApplicationController
+
+  def create
+    @client = Client.new(params[:client])
+    if @client.save
+      # ...
+    else
+      flash.now[:error] = "Could not save client"
+      render :action => "new"
+    end
+  end
+
+end
+</ruby>
+
+h3. Cookies
+
+Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the +cookies+ method, which - much like the +session+ - works like a hash:
+
+<ruby>
+class CommentsController < ApplicationController
+
+  def new
+    #Auto-fill the commenter's name if it has been stored in a cookie
+    @comment = Comment.new(:name => cookies[:commenter_name])
+  end
+
+  def create
+    @comment = Comment.new(params[:comment])
+    if @comment.save
+      flash[:notice] = "Thanks for your comment!"
+      if params[:remember_name]
+        # Remember the commenter's name
+        cookies[:commenter_name] = @comment.name
+      else
+        # Don't remember, and delete the name if it has been remembered before
+        cookies.delete(:commenter_name)
+      end
+      redirect_to @comment.article
+    else
+      render :action => "new"
+    end
+  end
+
+end
+</ruby>
+
+Note that while for session values you set the key to +nil+, to delete a cookie value you should use +cookies.delete(:key)+.
+
+h3. Filters
+
+Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+private
+
+  def require_login
+    unless logged_in?
+      flash[:error] = "You must be logged in to access this section"
+      redirect_to new_login_url # Prevents the current action from running
+    end
+  end
+
+  # The logged_in? method simply returns true if the user is logged in and
+  # false otherwise. It does this by "booleanizing" the current_user method
+  # we created previously using a double ! operator. Note that this is not
+  # common in Ruby and is discouraged unless you really mean to convert something
+  # into true or false.
+  def logged_in?
+    !!current_user
+  end
+
+end
+</ruby>
+
+The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the +before_filter+ method:
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+  before_filter :require_login
+
+end
+</ruby>
+
+In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with +skip_before_filter+:
+
+<ruby>
+class LoginsController < Application
+
+  skip_before_filter :require_login, :only => [:new, :create]
+
+end
+</ruby>
+
+Now, the LoginsController's +new+ and +create+ actions will work as before without requiring the user to be logged in. The +:only+ option is used to only skip this filter for these actions, and there is also an +:except+ option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+
+h4. After Filters and Around Filters
+
+In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
+
+<ruby>
+# Example taken from the Rails API filter documentation:
+# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
+class ApplicationController < Application
+
+  around_filter :catch_exceptions
+
+private
+
+  def catch_exceptions
+    yield
+  rescue => exception
+    logger.debug "Caught exception! #{exception}"
+    raise
+  end
+
+end
+</ruby>
+
+h4. Other Ways to Use Filters
+
+While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
+
+The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the +require_login+ filter from above could be rewritten to use a block:
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+  before_filter { |controller| redirect_to new_login_url unless controller.send(:logged_in?) }
+
+end
+</ruby>
+
+Note that the filter in this case uses +send+ because the +logged_in?+ method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
+
+The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+  before_filter LoginFilter
+
+end
+
+class LoginFilter
+
+  def self.filter(controller)
+    unless logged_in?
+      controller.flash[:error] = "You must be logged in to access this section"
+      controller.redirect_to controller.new_login_url
+    end
+  end
+
+end
+</ruby>
+
+Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method +filter+ which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same +filter+ method, which will get run in the same way. The method must +yield+ to execute the action. Alternatively, it can have both a +before+ and an +after+ method that are run before and after the action.
+
+The Rails API documentation has "more information on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html.
+
+h3. Verification
+
+Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
+
+Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
+
+<ruby>
+class LoginsController < ApplicationController
+
+  verify :params => [:username, :password],
+         :render => {:action => "new"},
+         :add_flash => {:error => "Username and password required to log in"}
+
+  def create
+    @user = User.authenticate(params[:username], params[:password])
+    if @user
+      flash[:notice] = "You're logged in"
+      redirect_to root_url
+    else
+      render :action => "new"
+    end
+  end
+
+end
+</ruby>
+
+Now the +create+ action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the +new+ action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the +:only+ and +:except+ options just like a filter:
+
+<ruby>
+class LoginsController < ApplicationController
+
+  verify :params => [:username, :password],
+         :render => {:action => "new"},
+         :add_flash => {:error => "Username and password required to log in"},
+         :only => :create # Only run this verification for the "create" action
+
+end
+</ruby>
+
+h3. Request Forgery Protection
+
+Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
+
+If you generate a form like this:
+
+<ruby>
+<% form_for @user do |f| -%>
+  <%= f.text_field :username %>
+  <%= f.text_field :password -%>
+<% end -%>
+</ruby>
+
+You will see how the token gets added as a hidden field:
+
+<ruby>
+<form action="/users/1" method="post">
+<div><!-- ... --><input type="hidden" value="67250ab105eb5ad10851c00a5621854a23af5489" name="authenticity_token"/></div>
+<!-- Fields -->
+</form>
+</ruby>
+
+Rails adds this token to every form that's generated using the "form helpers":form_helpers.html, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method +form_authenticity_token+:
+
+TODO: Add line below as description
+
+Add a JavaScript variable containing the token for use with Ajax
+
+<erb>
+<%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %>
+</erb>
+
+The "Security Guide":security.html has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
+
+h3. The request and response Objects
+
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of AbstractRequest and the +response+ method returns a +response+ object representing what is going to be sent back to the client.
+
+h4. The request Object
+
+The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html. Among the properties that you can access on this object are:
+
+* host - The hostname used for this request.
+* domain(n=2) - The hostname's first +n+ segments, starting from the right (the TLD)
+* format - The content type requested by the client.
+* method - The HTTP method used for the request.
+* get?, post?, put?, delete?, head? - Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.
+* headers - Returns a hash containing the headers associated with the request.
+* port - The port number (integer) used for the request.
+* protocol - Returns a string containing the prototol used plus "://", for example "http://"
+* query_string - The query string part of the URL - everything after "?".
+* remote_ip - The IP address of the client.
+* url - The entire URL used for the request.
+
+h5. path_parameters, query_parameters and request_parameters
+
+Rails collects all of the parameters sent along with the request in the +params+ hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The +query_parameters+ hash contains parameters that were sent as part of the query string while the +request_parameters+ hash contains parameters sent as part of the post body. The +path_parameters+ hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
+
+h4. The response Object
+
+The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
+
+* body - This is the string of data being sent back to the client. This is most often HTML.
+* status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
+* location - The URL the client is being redirected to, if any.
+* content_type - The content type of the response.
+* charset - The character set being used for the response. Default is "utf8".
+* headers - Headers used for the response.
+
+h5. Setting Custom Headers
+
+If you want to set custom headers for a response then +response.headers+ is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to +headers+ with the name and value:
+
+<ruby>
+response.headers["Content-Type"] = "application/pdf"
+</ruby>
+
+h3. HTTP Authentications
+
+Rails comes with two built-in HTTP authentication mechanisms :
+
+* Basic Authentication
+* Digest Authentication
+
+h4. HTTP Basic Authentication
+
+HTTP Basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +authenticate_or_request_with_http_basic+.
+
+<ruby>
+class AdminController < ApplicationController
+
+  USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
+
+  before_filter :authenticate
+
+  private
+
+  def authenticate
+    authenticate_or_request_with_http_basic do |username, password|
+      username == USERNAME && Digest::SHA1.hexdigest(password) == PASSWORD
+    end
+  end
+
+end
+</ruby>
+
+With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.
+
+h4. HTTP Digest Authentication
+
+HTTP Digest authentication is superior to the Basic authentication as it does not require the client to send unencrypted password over the network. Using Digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
+
+<ruby>
+class AdminController < ApplicationController
+
+  USERS = { "lifo" => "world" }
+
+  before_filter :authenticate
+
+  private
+
+  def authenticate
+    authenticate_or_request_with_http_digest do |username|
+      USERS[username]
+    end
+  end
+
+end
+</ruby>
+
+As seen in the example above, +authenticate_or_request_with_http_digest+ block takes only one argument - the username. And the block returns the password. Returning +false+ or +nil+ from the +authenticate_or_request_with_http_digest+ will cause authentication failure.
+
+h3. Streaming and File Downloads
+
+Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the +send_data+ and the +send_file+ methods, that will both stream data to the client. +send_file+ is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
+
+To stream data to the client, use +send_data+:
+
+<ruby>
+require "prawn"
+class ClientsController < ApplicationController
+
+  # Generate a PDF document with information on the client and return it.
+  # The user will get the PDF as a file download.
+  def download_pdf
+    client = Client.find(params[:id])
+    send_data(generate_pdf, :filename => "#{client.name}.pdf", :type => "application/pdf")
+  end
+
+private
+
+  def generate_pdf(client)
+    Prawn::Document.new do
+      text client.name, :align => :center
+      text "Address: #{client.address}"
+      text "Email: #{client.email}"
+    end.render
+  end
+
+end
+</ruby>
+
+The +download_pdf+ action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the +:disposition+ option to "inline". The opposite and default value for this option is "attachment".
+
+h4. Sending Files
+
+If you want to send a file that already exists on disk, use the +send_file+ method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.
+
+<ruby>
+class ClientsController < ApplicationController
+
+  # Stream a file that has already been generated and stored on disk
+  def download_pdf
+    client = Client.find(params[:id])
+    send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf", :filename => "#{client.name}.pdf", :type => "application/pdf")
+  end
+
+end
+</ruby>
+
+This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option.
+
+WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
+
+TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the +:x_sendfile+ option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the +X-Sendfile+ header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files.
+
+h4. RESTful Downloads
+
+While +send_data+ works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the +show+ action, without any streaming:
+
+<ruby>
+class ClientsController < ApplicationController
+
+  # The user can request to receive this resource as HTML or PDF.
+  def show
+    @client = Client.find(params[:id])
+
+    respond_to do |format|
+      format.html
+      format.pdf{ render :pdf => generate_pdf(@client) }
+    end
+  end
+
+end
+</ruby>
+
+In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file +config/initializers/mime_types.rb+:
+
+<ruby>
+Mime::Type.register "application/pdf", :pdf
+</ruby>
+
+NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
+
+Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
+
+<ruby>
+GET /clients/1.pdf
+</ruby>
+
+h3. Parameter Filtering
+
+Rails keeps a log file for each environment (development, test and production) in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+  filter_parameter_logging :password
+
+end
+</ruby>
+
+The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
+
+h3. Rescue
+
+Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
+
+h4. The Default 500 and 404 Templates
+
+By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the +public+ folder, in +404.html+ and +500.html+ respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
+
+h4. rescue_from
+
+If you want to do something a bit more elaborate when catching errors, you can use +rescue_from+, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the +:with+ option. You can also use a block directly instead of an explicit Proc object.
+
+Here's how you can use +rescue_from+ to intercept all ActiveRecord::RecordNotFound errors and do something with them.
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
+
+private
+
+  def record_not_found
+    render :text => "404 Not Found", :status => 404
+  end
+
+end
+</ruby>
+
+Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
+
+<ruby>
+class ApplicationController < ActionController::Base
+
+  rescue_from User::NotAuthorized, :with => :user_not_authorized
+
+private
+
+  def user_not_authorized
+    flash[:error] = "You don't have access to this section."
+    redirect_to :back
+  end
+
+end
+
+class ClientsController < ApplicationController
+
+  # Check that the user has the right authorization to access clients.
+  before_filter :check_authorization
+
+  # Note how the actions don't have to worry about all the auth stuff.
+  def edit
+    @client = Client.find(params[:id])
+  end
+
+private
+
+  # If the user is not authorized, just throw the exception.
+  def check_authorization
+    raise User::NotAuthorized unless current_user.admin?
+  end
+
+end
+</ruby>
+
+NOTE: Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's "article":http://m.onkey.org/2008/7/20/rescue-from-dispatching on the subject for more information.
+
+h3. Changelog
+
+"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17
+
+* November 4, 2008: First release version by Tore Darell
-- 
cgit v1.2.3


From 984fbba5e8d24e0c2f33dd9d9818fb6bd1f8f591 Mon Sep 17 00:00:00 2001
From: James Miller <james@jkmillertech.com>
Date: Fri, 6 Feb 2009 07:44:34 -0800
Subject: Fix some spelling errors in Action Controller guide

---
 railties/guides/source/action_controller_overview.textile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 31a9c6819c..41b47ca553 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -76,7 +76,7 @@ class ClientsController < ActionController::Base
     if params[:status] = "activated"
       @clients = Client.activated
     else
-      @clients = Client.unativated
+      @clients = Client.unactivated
     end
   end
 
@@ -540,7 +540,7 @@ The request object contains a lot of useful information about the request coming
 * get?, post?, put?, delete?, head? - Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.
 * headers - Returns a hash containing the headers associated with the request.
 * port - The port number (integer) used for the request.
-* protocol - Returns a string containing the prototol used plus "://", for example "http://"
+* protocol - Returns a string containing the protocol used plus "://", for example "http://"
 * query_string - The query string part of the URL - everything after "?".
 * remote_ip - The IP address of the client.
 * url - The entire URL used for the request.
-- 
cgit v1.2.3


From 858aaa963c2f63dd9dd7bd853376caf57c70d575 Mon Sep 17 00:00:00 2001
From: Tore Darell <toredarell@gmail.com>
Date: Sat, 7 Feb 2009 00:24:01 +0100
Subject: Reword the session section to reflect that CookieStore has an ID and
 that you can change they :key and :secret

---
 .../guides/source/action_controller_overview.textile    | 17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 41b47ca553..9b8e1b4751 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -163,9 +163,11 @@ Your application has a session for each user in which you can store small amount
 * MemCacheStore - Stores the data in a memcache.
 * ActiveRecordStore - Stores the data in a database using Active Record.
 
-All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL).
+All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
 
-Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The CookieStore has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.
+For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
+
+The CookieStore can store around 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
 
 Read more about session storage in the "Security Guide":security.html.
 
@@ -176,6 +178,17 @@ If you need a different session storage mechanism, you can change it in the +con
 config.action_controller.session_store = :active_record_store
 </ruby>
 
+Rails sets up a session key (the name of the cookie) and (for the CookieStore) a secret key used when signing the session data. These can also be changed in +config/environment.rb+:
+
+<ruby>
+config.actioncontroller.session = {
+  :key => "_yourappname_session",
+  :secret => "g7tr273tr823ter823tr2qtr8q73w8q3trh76t878..."
+}
+</ruby>
+
+NOTE: Changing the secret when using the CookieStore will invalidate all existing sessions.
+
 h4. Accessing the Session
 
 In your controller you can access the session through the +session+ instance method.
-- 
cgit v1.2.3


From ecc9e86e8963ae4359bde4d0e8702fa51cd07d25 Mon Sep 17 00:00:00 2001
From: Tore Darell <toredarell@gmail.com>
Date: Sat, 7 Feb 2009 00:38:40 +0100
Subject: Remove <code> from inside <pre>

---
 railties/guides/source/action_controller_overview.textile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 9b8e1b4751..885c691efb 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -101,9 +101,9 @@ h4. Hash and Array Parameters
 
 The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:
 
-<pre><code>
+<pre>
 GET /clients?ids[]=1&ids[]=2&ids[]=3
-</code></pre>
+</pre>
 
 NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
 
-- 
cgit v1.2.3


From 01f82d62dcc32dd7ee0ecbac7505786dca941973 Mon Sep 17 00:00:00 2001
From: Xavier Noria <fxn@hashref.com>
Date: Sat, 7 Feb 2009 15:06:26 +0100
Subject: edged coverage of session storage configuration

---
 .../guides/source/action_controller_overview.textile | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 885c691efb..137349e2ff 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -171,19 +171,25 @@ The CookieStore can store around 4kB of data - much less than the others - but t
 
 Read more about session storage in the "Security Guide":security.html.
 
-If you need a different session storage mechanism, you can change it in the +config/environment.rb+ file:
+If you need a different session storage mechanism, you can change it in the +config/initializers/session_store.rb+ file:
 
 <ruby>
-# Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]
-config.action_controller.session_store = :active_record_store
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rake db:sessions:create")
+# ActionController::Base.session_store = :active_record_store
 </ruby>
 
-Rails sets up a session key (the name of the cookie) and (for the CookieStore) a secret key used when signing the session data. These can also be changed in +config/environment.rb+:
+Rails sets up a session key (the name of the cookie) and (for the CookieStore) a secret key used when signing the session data. These can also be changed in +config/initializers/session_store.rb+:
 
 <ruby>
-config.actioncontroller.session = {
-  :key => "_yourappname_session",
-  :secret => "g7tr273tr823ter823tr2qtr8q73w8q3trh76t878..."
+# Your secret key for verifying cookie session data integrity.
+# If you change this key, all old sessions will become invalid!
+# Make sure the secret is at least 30 characters and all random, 
+# no regular words or you'll be exposed to dictionary attacks.
+ActionController::Base.session = {
+  :key         => '_yourappname_session',
+  :secret      => '4f50711b8f0f49572...'
 }
 </ruby>
 
-- 
cgit v1.2.3


From 37411e9e57ed04a0c3683edf3e369b821b853922 Mon Sep 17 00:00:00 2001
From: Andreas Scherer <andreas_coder@freenet.de>
Date: Wed, 11 Feb 2009 15:49:32 +0100
Subject: Fix some formatting errors

for <code> elements
for (monospaced) displayed material
add some commas in enumerations.
---
 .../source/action_controller_overview.textile      | 50 +++++++++++-----------
 1 file changed, 26 insertions(+), 24 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 137349e2ff..f39d3088bd 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -63,12 +63,12 @@ ApplicationController inherits from ActionController::Base, which defines a numb
 
 h3. Parameters
 
-You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the +params+ hash in your controller:
+You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the +params+ hash in your controller:
 
 <ruby>
 class ClientsController < ActionController::Base
 
-  # This action uses query string parameters because it gets run by a HTTP
+  # This action uses query string parameters because it gets run by an HTTP
   # GET request, but this does not make any difference to the way in which
   # the parameters are accessed. The URL for this action would look like this
   # in order to list activated clients: /clients?status=activated
@@ -99,7 +99,7 @@ end
 
 h4. Hash and Array Parameters
 
-The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:
+The +params+ hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:
 
 <pre>
 GET /clients?ids[]=1&ids[]=2&ids[]=3
@@ -120,9 +120,9 @@ To send a hash you include the key name inside the brackets:
 </form>
 </html>
 
-The value of +params[:client]+ when this form is submitted  will be +{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}+. Note the nested hash in +params[:client][:address]+.
+When this form is submitted, the value of +params[:client]+ will be +{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}+. Note the nested hash in +params[:client][:address]+.
 
-Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.
+Note that the +params+ hash is actually an instance of HashWithIndifferentAccess from Active Support, which is a subclass of Hash that lets you use symbols and strings interchangeably as keys.
 
 h4. Routing Parameters
 
@@ -134,7 +134,7 @@ map.connect "/clients/:status", :controller => "clients", :action => "index", :f
 # ...
 </ruby>
 
-In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string in the same way +params[:action]+ will contain "index".
+In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string. In the same way +params[:action]+ will contain "index".
 
 h4. default_url_options
 
@@ -143,7 +143,7 @@ You can set global default parameters that will be used when generating URLs wit
 <ruby>
 class ApplicationController < ActionController::Base
 
-  #The options parameter is the hash passed in to +url_for+
+  # The options parameter is the hash passed in to 'url_for'
   def default_url_options(options)
     {:locale => I18n.locale}
   end
@@ -151,7 +151,7 @@ class ApplicationController < ActionController::Base
 end
 </ruby>
 
-These options will be used as a starting-point when generating, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
+These options will be used as a starting-point when generating URLs, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
 
 
 h3. Session
@@ -292,11 +292,13 @@ If you want a flash value to be carried over to another request, use the +keep+
 <ruby>
 class MainController < ApplicationController
 
-  # Let's say this action corresponds to root_url, but you want all requests here to be redirected to
-  # UsersController#index. If an action sets the flash and redirects here, the values would normally be
-  # lost when another redirect happens, but you can use keep to make it persist for another request.
+  # Let's say this action corresponds to root_url, but you want all requests
+  # here to be redirected to UsersController#index. If an action sets the flash
+  # and redirects here, the values would normally be lost when another redirect
+  # happens, but you can use 'keep' to make it persist for another request.
   def index
-    flash.keep # Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice)
+    flash.keep # Will persist all flash values. You can also use a key to keep
+      # only that kind of value: flash.keep(:notice)
     redirect_to users_url
   end
 
@@ -331,7 +333,7 @@ Your application can store small amounts of data on the client - called cookies
 class CommentsController < ApplicationController
 
   def new
-    #Auto-fill the commenter's name if it has been stored in a cookie
+    # Auto-fill the commenter's name if it has been stored in a cookie
     @comment = Comment.new(:name => cookies[:commenter_name])
   end
 
@@ -446,7 +448,7 @@ end
 
 Note that the filter in this case uses +send+ because the +logged_in?+ method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
 
-The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
+The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
 
 <ruby>
 class ApplicationController < ActionController::Base
@@ -546,7 +548,7 @@ The "Security Guide":security.html has more about this and a lot of other securi
 
 h3. The request and response Objects
 
-In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of AbstractRequest and the +response+ method returns a +response+ object representing what is going to be sent back to the client.
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of AbstractRequest and the +response+ method returns a response object representing what is going to be sent back to the client.
 
 h4. The request Object
 
@@ -564,7 +566,7 @@ The request object contains a lot of useful information about the request coming
 * remote_ip - The IP address of the client.
 * url - The entire URL used for the request.
 
-h5. path_parameters, query_parameters and request_parameters
+h5. path_parameters, query_parameters, and request_parameters
 
 Rails collects all of the parameters sent along with the request in the +params+ hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The +query_parameters+ hash contains parameters that were sent as part of the query string while the +request_parameters+ hash contains parameters sent as part of the post body. The +path_parameters+ hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
 
@@ -589,14 +591,14 @@ response.headers["Content-Type"] = "application/pdf"
 
 h3. HTTP Authentications
 
-Rails comes with two built-in HTTP authentication mechanisms :
+Rails comes with two built-in HTTP authentication mechanisms:
 
 * Basic Authentication
 * Digest Authentication
 
 h4. HTTP Basic Authentication
 
-HTTP Basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +authenticate_or_request_with_http_basic+.
+HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +authenticate_or_request_with_http_basic+.
 
 <ruby>
 class AdminController < ApplicationController
@@ -616,11 +618,11 @@ class AdminController < ApplicationController
 end
 </ruby>
 
-With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.
+With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
 
 h4. HTTP Digest Authentication
 
-HTTP Digest authentication is superior to the Basic authentication as it does not require the client to send unencrypted password over the network. Using Digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
+HTTP digest authentication is superior to the basic authentication as it does not require the client to send unencrypted password over the network. Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
 
 <ruby>
 class AdminController < ApplicationController
@@ -640,11 +642,11 @@ class AdminController < ApplicationController
 end
 </ruby>
 
-As seen in the example above, +authenticate_or_request_with_http_digest+ block takes only one argument - the username. And the block returns the password. Returning +false+ or +nil+ from the +authenticate_or_request_with_http_digest+ will cause authentication failure.
+As seen in the example above, the +authenticate_or_request_with_http_digest+ block takes only one argument - the username. And the block returns the password. Returning +false+ or +nil+ from the +authenticate_or_request_with_http_digest+ will cause authentication failure.
 
 h3. Streaming and File Downloads
 
-Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the +send_data+ and the +send_file+ methods, that will both stream data to the client. +send_file+ is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.
+Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the +send_data+ and the +send_file+ methods, which will both stream data to the client. +send_file+ is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.
 
 To stream data to the client, use +send_data+:
 
@@ -732,7 +734,7 @@ GET /clients/1.pdf
 
 h3. Parameter Filtering
 
-Rails keeps a log file for each environment (development, test and production) in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+Rails keeps a log file for each environment (development, test, and production) in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
 
 <ruby>
 class ApplicationController < ActionController::Base
@@ -742,7 +744,7 @@ class ApplicationController < ActionController::Base
 end
 </ruby>
 
-The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
+The method works recursively through all levels of the +params+ hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
 
 h3. Rescue
 
-- 
cgit v1.2.3


From d04b8ee53081974d2a1ed71906bc0e3b5571e6ca Mon Sep 17 00:00:00 2001
From: Xavier Noria <fxn@hashref.com>
Date: Tue, 17 Feb 2009 01:31:37 +0100
Subject: yet another pass on the action controller guide

---
 .../source/action_controller_overview.textile      | 333 +++++++++------------
 1 file changed, 144 insertions(+), 189 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index f39d3088bd..4c21d2cda6 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -12,9 +12,9 @@ In this guide you will learn how controllers work and how they fit into the requ
 
 endprologue.
 
-h3. What Does a Controller do?
+h3. What Does a Controller Do?
 
-Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.
+Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
 
 For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
 
@@ -24,31 +24,16 @@ NOTE: For more details on the routing process, see "Rails Routing from the Outsi
 
 h3. Methods and Actions
 
-A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.
+A controller is a Ruby class which inherits from +ApplicationController+ and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.
 
 <ruby>
 class ClientsController < ApplicationController
-
-  # Actions are public methods
   def new
   end
-
-  # Action methods are responsible for producing output
-  def edit
-  end
-
-# Helper methods are private and can not be used as actions
-private
-
-  def foo
-  end
-
 end
 </ruby>
 
-There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.
-
-As an example, if a user goes to +/clients/new+ in your application to add a new client, Rails will create an instance of ClientsController and run the +new+ method. Note that the empty method from the example above could work just fine because Rails will by default render the +new.html.erb+ view unless the action says otherwise. The +new+ method could make available to the view a +@client+ instance variable by creating a new Client:
+As an example, if a user goes to +/clients/new+ in your application to add a new client, Rails will create an instance of +ClientsController+ and run the +new+ method. Note that the empty method from the example above could work just fine because Rails will by default render the +new.html.erb+ view unless the action says otherwise. The +new+ method could make available to the view a +@client+ instance variable by creating a new +Client+:
 
 <ruby>
 def new
@@ -58,8 +43,9 @@ end
 
 The "Layouts & rendering guide":layouts_and_rendering.html explains this in more detail.
 
-ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
++ApplicationController+ inherits from +ActionController::Base+, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
 
+Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters.
 
 h3. Parameters
 
@@ -67,11 +53,11 @@ You will probably want to access data sent in by the user or other parameters in
 
 <ruby>
 class ClientsController < ActionController::Base
-
-  # This action uses query string parameters because it gets run by an HTTP
-  # GET request, but this does not make any difference to the way in which
-  # the parameters are accessed. The URL for this action would look like this
-  # in order to list activated clients: /clients?status=activated
+  # This action uses query string parameters because it gets run
+  # by an HTTP GET request, but this does not make any difference
+  # to the way in which the parameters are accessed. The URL for
+  # this action would look like this in order to list activated
+  # clients: /clients?status=activated
   def index
     if params[:status] = "activated"
       @clients = Client.activated
@@ -80,24 +66,24 @@ class ClientsController < ActionController::Base
     end
   end
 
-  # This action uses POST parameters. They are most likely coming from an HTML
-  # form which the user has submitted. The URL for this RESTful request will
-  # be "/clients", and the data will be sent as part of the request body.
+  # This action uses POST parameters. They are most likely coming
+  # from an HTML form which the user has submitted. The URL for
+  # this RESTful request will be "/clients", and the data will be
+  # sent as part of the request body.
   def create
     @client = Client.new(params[:client])
     if @client.save
       redirect_to @client
     else
-      # This line overrides the default rendering behavior, which would have been
-      # to render the "create" view.
+      # This line overrides the default rendering behavior, which
+      # would have been to render the "create" view.
       render :action => "new"
     end
   end
-
 end
 </ruby>
 
-h4. Hash and Array Parameters
+h4. Hash and array parameters
 
 The +params+ hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:
 
@@ -105,7 +91,7 @@ The +params+ hash is not limited to one-dimensional keys and values. It can cont
 GET /clients?ids[]=1&ids[]=2&ids[]=3
 </pre>
 
-NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
+NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as "[" and "]" are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
 
 The value of +params[:ids]+ will now be +["1", "2", "3"]+. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
 
@@ -120,18 +106,19 @@ To send a hash you include the key name inside the brackets:
 </form>
 </html>
 
-When this form is submitted, the value of +params[:client]+ will be +{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}+. Note the nested hash in +params[:client][:address]+.
+When this form is submitted, the value of +params[:client]+ will be <tt>{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}</tt>. Note the nested hash in +params[:client][:address]+.
 
-Note that the +params+ hash is actually an instance of HashWithIndifferentAccess from Active Support, which is a subclass of Hash that lets you use symbols and strings interchangeably as keys.
+Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.
 
 h4. Routing Parameters
 
 The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL:
 
 <ruby>
-# ...
-map.connect "/clients/:status", :controller => "clients", :action => "index", :foo => "bar"
-# ...
+map.connect "/clients/:status", 
+  :controller => "clients",
+  :action => "index",
+  :foo => "bar"
 </ruby>
 
 In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string. In the same way +params[:action]+ will contain "index".
@@ -142,16 +129,14 @@ You can set global default parameters that will be used when generating URLs wit
 
 <ruby>
 class ApplicationController < ActionController::Base
-
   # The options parameter is the hash passed in to 'url_for'
   def default_url_options(options)
     {:locale => I18n.locale}
   end
-
 end
 </ruby>
 
-These options will be used as a starting-point when generating URLs, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
+These options will be used as a starting-point when generating URLs, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on +ApplicationController+ so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
 
 
 h3. Session
@@ -165,9 +150,9 @@ Your application has a session for each user in which you can store small amount
 
 All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
 
-For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
+For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
 
-The CookieStore can store around 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
+The CookieStore can store around 4kB of data -- much less than the others -- but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
 
 Read more about session storage in the "Security Guide":security.html.
 
@@ -195,7 +180,7 @@ ActionController::Base.session = {
 
 NOTE: Changing the secret when using the CookieStore will invalidate all existing sessions.
 
-h4. Accessing the Session
+h4. Accessing the session
 
 In your controller you can access the session through the +session+ instance method.
 
@@ -208,13 +193,14 @@ class ApplicationController < ActionController::Base
 
 private
 
-  # Finds the User with the ID stored in the session with the key :current_user_id
-  # This is a common way to handle user login in a Rails application; logging in sets the
-  # session value and logging out removes it.
+  # Finds the User with the ID stored in the session with the key
+  # :current_user_id This is a common way to handle user login in
+  # a Rails application; logging in sets the session value and
+  # logging out removes it.
   def current_user
-    @_current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
+    @_current_user ||= session[:current_user_id] &&
+      User.find(session[:current_user_id])
   end
-
 end
 </ruby>
 
@@ -222,16 +208,15 @@ To store something in the session, just assign it to the key like a hash:
 
 <ruby>
 class LoginsController < ApplicationController
-
   # "Create" a login, aka "log the user in"
   def create
-    if user = User.authenticate(params[:username, params[:password])
-      # Save the user ID in the session so it can be used in subsequent requests
+    if user = User.authenticate(params[:username], params[:password])
+      # Save the user ID in the session so it can be used in
+      # subsequent requests
       session[:current_user_id] = user.id
       redirect_to root_url
     end
   end
-
 end
 </ruby>
 
@@ -239,14 +224,12 @@ To remove something from the session, assign that key to be +nil+:
 
 <ruby>
 class LoginsController < ApplicationController
-
   # "Delete" a login, aka "log the user out"
   def destroy
     # Remove the user id from the session
     session[:current_user_id] = nil
     redirect_to root_url
   end
-
 end
 </ruby>
 
@@ -258,13 +241,11 @@ The flash is a special part of the session which is cleared with each request. T
 
 <ruby>
 class LoginsController < ApplicationController
-
   def destroy
     session[:current_user_id] = nil
     flash[:notice] = "You have successfully logged out"
     redirect_to root_url
   end
-
 end
 </ruby>
 
@@ -291,17 +272,19 @@ If you want a flash value to be carried over to another request, use the +keep+
 
 <ruby>
 class MainController < ApplicationController
-
-  # Let's say this action corresponds to root_url, but you want all requests
-  # here to be redirected to UsersController#index. If an action sets the flash
-  # and redirects here, the values would normally be lost when another redirect
-  # happens, but you can use 'keep' to make it persist for another request.
+  # Let's say this action corresponds to root_url, but you want
+  # all requests here to be redirected to UsersController#index.
+  # If an action sets the flash and redirects here, the values
+  # would normally be lost when another redirect happens, but you
+  # can use 'keep' to make it persist for another request.
   def index
-    flash.keep # Will persist all flash values. You can also use a key to keep
-      # only that kind of value: flash.keep(:notice)
+    # Will persist all flash values.
+    flash.keep
+
+    # You can also use a key to keep only some kind of value. 
+    # flash.keep(:notice)
     redirect_to users_url
   end
-
 end
 </ruby>
 
@@ -311,7 +294,6 @@ By default, adding values to the flash will make them available to the next requ
 
 <ruby>
 class ClientsController < ApplicationController
-
   def create
     @client = Client.new(params[:client])
     if @client.save
@@ -321,17 +303,15 @@ class ClientsController < ApplicationController
       render :action => "new"
     end
   end
-
 end
 </ruby>
 
 h3. Cookies
 
-Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the +cookies+ method, which - much like the +session+ - works like a hash:
+Your application can store small amounts of data on the client -- called cookies -- that will be persisted across requests and even sessions. Rails provides easy access to cookies via the +cookies+ method, which -- much like the +session+ -- works like a hash:
 
 <ruby>
 class CommentsController < ApplicationController
-
   def new
     # Auto-fill the commenter's name if it has been stored in a cookie
     @comment = Comment.new(:name => cookies[:commenter_name])
@@ -342,10 +322,10 @@ class CommentsController < ApplicationController
     if @comment.save
       flash[:notice] = "Thanks for your comment!"
       if params[:remember_name]
-        # Remember the commenter's name
+        # Remember the commenter's name.
         cookies[:commenter_name] = @comment.name
       else
-        # Don't remember, and delete the name if it has been remembered before
+        # Delete cookie for the commenter's name cookie, if any.
         cookies.delete(:commenter_name)
       end
       redirect_to @comment.article
@@ -353,7 +333,6 @@ class CommentsController < ApplicationController
       render :action => "new"
     end
   end
-
 end
 </ruby>
 
@@ -361,78 +340,70 @@ Note that while for session values you set the key to +nil+, to delete a cookie
 
 h3. Filters
 
-Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
+Filters are methods that are run before, after or "around" a controller action. 
+
+Filters are inherited, so if you set a filter on +ApplicationController+, it will be run on every controller in your application. 
+
+Before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
 
 <ruby>
 class ApplicationController < ActionController::Base
+  before_filter :require_login
 
 private
-
   def require_login
     unless logged_in?
       flash[:error] = "You must be logged in to access this section"
-      redirect_to new_login_url # Prevents the current action from running
+      redirect_to new_login_url # halts request cycle
     end
   end
 
-  # The logged_in? method simply returns true if the user is logged in and
-  # false otherwise. It does this by "booleanizing" the current_user method
-  # we created previously using a double ! operator. Note that this is not
-  # common in Ruby and is discouraged unless you really mean to convert something
-  # into true or false.
+  # The logged_in? method simply returns true if the user is logged
+  # in and false otherwise. It does this by "booleanizing" the
+  # current_user method we created previously using a double ! operator.
+  # Note that this is not common in Ruby and is discouraged unless you
+  # really mean to convert something into true or false.
   def logged_in?
     !!current_user
   end
-
 end
 </ruby>
 
-The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the +before_filter+ method:
-
-<ruby>
-class ApplicationController < ActionController::Base
-
-  before_filter :require_login
-
-end
-</ruby>
+The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.
 
-In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with +skip_before_filter+:
+In this example the filter is added to +ApplicationController+ and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with +skip_before_filter+:
 
 <ruby>
 class LoginsController < Application
-
   skip_before_filter :require_login, :only => [:new, :create]
-
 end
 </ruby>
 
-Now, the LoginsController's +new+ and +create+ actions will work as before without requiring the user to be logged in. The +:only+ option is used to only skip this filter for these actions, and there is also an +:except+ option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+Now, the +LoginsController+'s +new+ and +create+ actions will work as before without requiring the user to be logged in. The +:only+ option is used to only skip this filter for these actions, and there is also an +:except+ option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
 
-h4. After Filters and Around Filters
+h4. After filters and around filters
 
-In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
+In addition to before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running.
+
+Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
 
 <ruby>
 # Example taken from the Rails API filter documentation:
 # http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
 class ApplicationController < Application
-
   around_filter :catch_exceptions
 
 private
-
   def catch_exceptions
     yield
   rescue => exception
     logger.debug "Caught exception! #{exception}"
     raise
   end
-
 end
 </ruby>
 
-h4. Other Ways to Use Filters
+h4. Other ways to use filters
 
 While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
 
@@ -440,9 +411,9 @@ The first is to use a block directly with the *_filter methods. The block receiv
 
 <ruby>
 class ApplicationController < ActionController::Base
-
-  before_filter { |controller| redirect_to new_login_url unless controller.send(:logged_in?) }
-
+  before_filter do |controller|
+    redirect_to new_login_url unless controller.send(:logged_in?)
+  end
 end
 </ruby>
 
@@ -452,20 +423,16 @@ The second way is to use a class (actually, any object that responds to the righ
 
 <ruby>
 class ApplicationController < ActionController::Base
-
   before_filter LoginFilter
-
 end
 
 class LoginFilter
-
   def self.filter(controller)
-    unless logged_in?
-      controller.flash[:error] = "You must be logged in to access this section"
+    unless controller.send(:logged_in?)
+      controller.flash[:error] = "You must be logged in"
       controller.redirect_to controller.new_login_url
     end
   end
-
 end
 </ruby>
 
@@ -475,16 +442,17 @@ The Rails API documentation has "more information on using filters":http://api.r
 
 h3. Verification
 
-Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
+Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHTTPRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
 
 Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
 
 <ruby>
 class LoginsController < ApplicationController
-
   verify :params => [:username, :password],
          :render => {:action => "new"},
-         :add_flash => {:error => "Username and password required to log in"}
+         :add_flash => {
+           :error => "Username and password required to log in"
+         }
 
   def create
     @user = User.authenticate(params[:username], params[:password])
@@ -495,7 +463,6 @@ class LoginsController < ApplicationController
       render :action => "new"
     end
   end
-
 end
 </ruby>
 
@@ -503,18 +470,22 @@ Now the +create+ action won't run unless the "username" and "password" parameter
 
 <ruby>
 class LoginsController < ApplicationController
-
   verify :params => [:username, :password],
          :render => {:action => "new"},
-         :add_flash => {:error => "Username and password required to log in"},
-         :only => :create # Only run this verification for the "create" action
-
+         :add_flash => {
+           :error => "Username and password required to log in"
+         },
+         :only => :create # Run only for the "create" action
 end
 </ruby>
 
 h3. Request Forgery Protection
 
-Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
+Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission.
+
+The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests.
+
+The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
 
 If you generate a form like this:
 
@@ -527,30 +498,26 @@ If you generate a form like this:
 
 You will see how the token gets added as a hidden field:
 
-<ruby>
+<html>
 <form action="/users/1" method="post">
-<div><!-- ... --><input type="hidden" value="67250ab105eb5ad10851c00a5621854a23af5489" name="authenticity_token"/></div>
-<!-- Fields -->
+<input type="hidden" 
+       value="67250ab105eb5ad10851c00a5621854a23af5489"
+       name="authenticity_token"/>
+<!-- fields -->
 </form>
-</ruby>
+</html>
 
 Rails adds this token to every form that's generated using the "form helpers":form_helpers.html, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method +form_authenticity_token+:
 
-TODO: Add line below as description
-
-Add a JavaScript variable containing the token for use with Ajax
-
-<erb>
-<%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %>
-</erb>
+The +form_authenticity_token+ generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls.
 
 The "Security Guide":security.html has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
 
-h3. The request and response Objects
+h3. The Request and Response Objects
 
-In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of AbstractRequest and the +response+ method returns a response object representing what is going to be sent back to the client.
+In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of +AbstractRequest+ and the +response+ method returns a response object representing what is going to be sent back to the client.
 
-h4. The request Object
+h4. The +request+ object
 
 The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html. Among the properties that you can access on this object are:
 
@@ -566,11 +533,11 @@ The request object contains a lot of useful information about the request coming
 * remote_ip - The IP address of the client.
 * url - The entire URL used for the request.
 
-h5. path_parameters, query_parameters, and request_parameters
+h5. +path_parameters+, +query_parameters+, and +request_parameters+
 
 Rails collects all of the parameters sent along with the request in the +params+ hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The +query_parameters+ hash contains parameters that were sent as part of the query string while the +request_parameters+ hash contains parameters sent as part of the post body. The +path_parameters+ hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
 
-h4. The response Object
+h4. The response object
 
 The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
 
@@ -578,12 +545,12 @@ The response object is not usually used directly, but is built up during the exe
 * status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
 * location - The URL the client is being redirected to, if any.
 * content_type - The content type of the response.
-* charset - The character set being used for the response. Default is "utf8".
+* charset - The character set being used for the response. Default is "utf-8".
 * headers - Headers used for the response.
 
-h5. Setting Custom Headers
+h5. Setting custom headers
 
-If you want to set custom headers for a response then +response.headers+ is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to +headers+ with the name and value:
+If you want to set custom headers for a response then +response.headers+ is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to +response.headers+ this way:
 
 <ruby>
 response.headers["Content-Type"] = "application/pdf"
@@ -596,49 +563,44 @@ Rails comes with two built-in HTTP authentication mechanisms:
 * Basic Authentication
 * Digest Authentication
 
-h4. HTTP Basic Authentication
+h4. HTTP basic authentication
 
 HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +authenticate_or_request_with_http_basic+.
 
 <ruby>
 class AdminController < ApplicationController
-
-  USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
+  USERNAME, PASSWORD = "humbaba", "5baa61e4"
 
   before_filter :authenticate
 
-  private
-
+private
   def authenticate
     authenticate_or_request_with_http_basic do |username, password|
-      username == USERNAME && Digest::SHA1.hexdigest(password) == PASSWORD
+      username == USERNAME &&
+      Digest::SHA1.hexdigest(password) == PASSWORD
     end
   end
-
 end
 </ruby>
 
-With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
+With this in place, you can create namespaced controllers that inherit from +AdminController+. The before filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
 
-h4. HTTP Digest Authentication
+h4. HTTP digest authentication
 
-HTTP digest authentication is superior to the basic authentication as it does not require the client to send unencrypted password over the network. Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
+HTTP digest authentication is superior to the basic authentication as it does not require the client to send unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
 
 <ruby>
 class AdminController < ApplicationController
-
   USERS = { "lifo" => "world" }
 
   before_filter :authenticate
 
-  private
-
+private
   def authenticate
     authenticate_or_request_with_http_digest do |username|
       USERS[username]
     end
   end
-
 end
 </ruby>
 
@@ -653,12 +615,13 @@ To stream data to the client, use +send_data+:
 <ruby>
 require "prawn"
 class ClientsController < ApplicationController
-
-  # Generate a PDF document with information on the client and return it.
-  # The user will get the PDF as a file download.
+  # Generates a PDF document with information on the client and
+  # returns it. The user will get the PDF as a file download.
   def download_pdf
     client = Client.find(params[:id])
-    send_data(generate_pdf, :filename => "#{client.name}.pdf", :type => "application/pdf")
+    send_data(generate_pdf, 
+              :filename => "#{client.name}.pdf",
+              :type => "application/pdf")
   end
 
 private
@@ -670,51 +633,48 @@ private
       text "Email: #{client.email}"
     end.render
   end
-
 end
 </ruby>
 
-The +download_pdf+ action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the +:disposition+ option to "inline". The opposite and default value for this option is "attachment".
+The +download_pdf+ action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the +:disposition+ option to "inline". The opposite and default value for this option is "attachment".
 
-h4. Sending Files
+h4. Sending files
 
-If you want to send a file that already exists on disk, use the +send_file+ method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.
+If you want to send a file that already exists on disk, use the +send_file+ method.
 
 <ruby>
 class ClientsController < ApplicationController
-
-  # Stream a file that has already been generated and stored on disk
+  # Stream a file that has already been generated and stored on disk.
   def download_pdf
     client = Client.find(params[:id])
-    send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf", :filename => "#{client.name}.pdf", :type => "application/pdf")
+    send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf",
+              :filename => "#{client.name}.pdf",
+              :type => "application/pdf")
   end
-
 end
 </ruby>
 
 This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option.
 
-WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
+WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
 
-TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the +:x_sendfile+ option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the +X-Sendfile+ header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files.
+TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the +:x_sendfile+ option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the +X-Sendfile+ header for this to work.
 
-h4. RESTful Downloads
+h4. RESTful downloads
 
 While +send_data+ works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the +show+ action, without any streaming:
 
 <ruby>
 class ClientsController < ApplicationController
-
   # The user can request to receive this resource as HTML or PDF.
   def show
     @client = Client.find(params[:id])
 
     respond_to do |format|
       format.html
-      format.pdf{ render :pdf => generate_pdf(@client) }
+      format.pdf { render :pdf => generate_pdf(@client) }
     end
   end
-
 end
 </ruby>
 
@@ -728,19 +688,17 @@ NOTE: Configuration files are not reloaded on each request, so you have to resta
 
 Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
 
-<ruby>
+<shell>
 GET /clients/1.pdf
-</ruby>
+</shell>
 
 h3. Parameter Filtering
 
-Rails keeps a log file for each environment (development, test, and production) in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
 
 <ruby>
 class ApplicationController < ActionController::Base
-
   filter_parameter_logging :password
-
 end
 </ruby>
 
@@ -748,29 +706,30 @@ The method works recursively through all levels of the +params+ hash and takes a
 
 h3. Rescue
 
-Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
+Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception.
 
-h4. The Default 500 and 404 Templates
+Rails' default exception handling displays a "500 Server Error" message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
+
+h4. The default 500 and 404 templates
 
 By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the +public+ folder, in +404.html+ and +500.html+ respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
 
-h4. rescue_from
+h4. +rescue_from+
+
+If you want to do something a bit more elaborate when catching errors, you can use +rescue_from+, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
 
-If you want to do something a bit more elaborate when catching errors, you can use +rescue_from+, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the +:with+ option. You can also use a block directly instead of an explicit Proc object.
+When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a +Proc+ object passed to the +:with+ option. You can also use a block directly instead of an explicit +Proc+ object.
 
-Here's how you can use +rescue_from+ to intercept all ActiveRecord::RecordNotFound errors and do something with them.
+Here's how you can use +rescue_from+ to intercept all +ActiveRecord::RecordNotFound+ errors and do something with them.
 
 <ruby>
 class ApplicationController < ActionController::Base
-
   rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
 
 private
-
   def record_not_found
     render :text => "404 Not Found", :status => 404
   end
-
 end
 </ruby>
 
@@ -778,20 +737,16 @@ Of course, this example is anything but elaborate and doesn't improve on the def
 
 <ruby>
 class ApplicationController < ActionController::Base
-
   rescue_from User::NotAuthorized, :with => :user_not_authorized
 
 private
-
   def user_not_authorized
     flash[:error] = "You don't have access to this section."
     redirect_to :back
   end
-
 end
 
 class ClientsController < ApplicationController
-
   # Check that the user has the right authorization to access clients.
   before_filter :check_authorization
 
@@ -801,19 +756,19 @@ class ClientsController < ApplicationController
   end
 
 private
-
   # If the user is not authorized, just throw the exception.
   def check_authorization
     raise User::NotAuthorized unless current_user.admin?
   end
-
 end
 </ruby>
 
-NOTE: Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's "article":http://m.onkey.org/2008/7/20/rescue-from-dispatching on the subject for more information.
+NOTE: Certain exceptions are only rescuable from the +ApplicationController+ class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's "article":http://m.onkey.org/2008/7/20/rescue-from-dispatching on the subject for more information.
 
 h3. Changelog
 
 "Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17
 
+* February 17, 2009: Yet another proofread by Xavier Noria.
+
 * November 4, 2008: First release version by Tore Darell
-- 
cgit v1.2.3


From d5376a247f804b331f8157c461c61213e3c1ce35 Mon Sep 17 00:00:00 2001
From: Andreas Scherer <andreas_coder@freenet.de>
Date: Tue, 17 Feb 2009 11:56:18 +0100
Subject: Fix a programming error.

Assignment and equality are not the same.
---
 railties/guides/source/action_controller_overview.textile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 4c21d2cda6..f9b7a3fe14 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -59,7 +59,7 @@ class ClientsController < ActionController::Base
   # this action would look like this in order to list activated
   # clients: /clients?status=activated
   def index
-    if params[:status] = "activated"
+    if params[:status] == "activated"
       @clients = Client.activated
     else
       @clients = Client.unactivated
-- 
cgit v1.2.3


From 5c4af5973228e9e2d4aafbbcb89cfd08afb2370c Mon Sep 17 00:00:00 2001
From: Andreas Scherer <andreas_coder@freenet.de>
Date: Tue, 17 Feb 2009 14:04:42 +0100
Subject: Use tables for object properties and their purposes.

Enumeration lists with bipartite entries could be harder to read than
two-column tables.
---
 .../source/action_controller_overview.textile      | 36 ++++++++++++----------
 1 file changed, 19 insertions(+), 17 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index f9b7a3fe14..84d98dd6ed 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -521,17 +521,18 @@ h4. The +request+ object
 
 The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html. Among the properties that you can access on this object are:
 
-* host - The hostname used for this request.
-* domain(n=2) - The hostname's first +n+ segments, starting from the right (the TLD)
-* format - The content type requested by the client.
-* method - The HTTP method used for the request.
-* get?, post?, put?, delete?, head? - Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.
-* headers - Returns a hash containing the headers associated with the request.
-* port - The port number (integer) used for the request.
-* protocol - Returns a string containing the protocol used plus "://", for example "http://"
-* query_string - The query string part of the URL - everything after "?".
-* remote_ip - The IP address of the client.
-* url - The entire URL used for the request.
+|_.Property of +request+|_.Purpose|
+|host|The hostname used for this request.|
+|domain(n=2)|The hostname's first +n+ segments, starting from the right (the TLD).|
+|format|The content type requested by the client.|
+|method|The HTTP method used for the request.|
+|get?, post?, put?, delete?, head?|Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.|
+|headers|Returns a hash containing the headers associated with the request.|
+|port|The port number (integer) used for the request.|
+|protocol|Returns a string containing the protocol used plus "://", for example "http://".|
+|query_string|The query string part of the URL, i.e., everything after "?".|
+|remote_ip|The IP address of the client.|
+|url|The entire URL used for the request.|
 
 h5. +path_parameters+, +query_parameters+, and +request_parameters+
 
@@ -541,12 +542,13 @@ h4. The response object
 
 The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
 
-* body - This is the string of data being sent back to the client. This is most often HTML.
-* status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
-* location - The URL the client is being redirected to, if any.
-* content_type - The content type of the response.
-* charset - The character set being used for the response. Default is "utf-8".
-* headers - Headers used for the response.
+|_.Property of +response+|_.Purpose|
+|body|This is the string of data being sent back to the client. This is most often HTML.|
+|status|The HTTP status code for the response, like 200 for a successful request or 404 for file not found.|
+|location|The URL the client is being redirected to, if any.|
+|content_type|The content type of the response.|
+|charset|The character set being used for the response. Default is "utf-8".|
+|headers|Headers used for the response.|
 
 h5. Setting custom headers
 
-- 
cgit v1.2.3


From 71947e30cc102e8512d76932dee015802a314d32 Mon Sep 17 00:00:00 2001
From: Andreas Scherer <andreas_coder@freenet.de>
Date: Tue, 17 Feb 2009 15:05:28 +0100
Subject: Fix two errors.

Missing article added.
Consistent (at least in this file) use of abbreviation.
---
 railties/guides/source/action_controller_overview.textile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 84d98dd6ed..949a962b27 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -589,7 +589,7 @@ With this in place, you can create namespaced controllers that inherit from +Adm
 
 h4. HTTP digest authentication
 
-HTTP digest authentication is superior to the basic authentication as it does not require the client to send unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
+HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
 
 <ruby>
 class AdminController < ApplicationController
@@ -656,7 +656,7 @@ class ClientsController < ApplicationController
 end
 </ruby>
 
-This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option.
+This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option.
 
 WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
 
-- 
cgit v1.2.3


From 8867a636b3d130bb1c9775ed1533260c0e26a326 Mon Sep 17 00:00:00 2001
From: Xavier Noria <fxn@hashref.com>
Date: Sat, 14 Mar 2009 17:17:28 +0100
Subject: revised case in titles of AC overview guide

---
 .../source/action_controller_overview.textile      | 30 +++++++++++-----------
 1 file changed, 15 insertions(+), 15 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 949a962b27..3ce6720815 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -83,7 +83,7 @@ class ClientsController < ActionController::Base
 end
 </ruby>
 
-h4. Hash and array parameters
+h4. Hash and Array Parameters
 
 The +params+ hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:
 
@@ -123,7 +123,7 @@ map.connect "/clients/:status",
 
 In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string. In the same way +params[:action]+ will contain "index".
 
-h4. default_url_options
+h4. +default_url_options+
 
 You can set global default parameters that will be used when generating URLs with +default_url_options+. To do this, define a method with that name in your controller:
 
@@ -180,7 +180,7 @@ ActionController::Base.session = {
 
 NOTE: Changing the secret when using the CookieStore will invalidate all existing sessions.
 
-h4. Accessing the session
+h4. Accessing the Session
 
 In your controller you can access the session through the +session+ instance method.
 
@@ -235,7 +235,7 @@ end
 
 To reset the entire session, use +reset_session+.
 
-h4. The flash
+h4. The Flash
 
 The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
 
@@ -288,7 +288,7 @@ class MainController < ApplicationController
 end
 </ruby>
 
-h5. flash.now
+h5. +flash.now+
 
 By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the +create+ action fails to save a resource and you render the +new+ template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use +flash.now+ in the same way you use the normal +flash+:
 
@@ -381,7 +381,7 @@ end
 
 Now, the +LoginsController+'s +new+ and +create+ actions will work as before without requiring the user to be logged in. The +:only+ option is used to only skip this filter for these actions, and there is also an +:except+ option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
 
-h4. After filters and around filters
+h4. After Filters and Around Filters
 
 In addition to before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running.
 
@@ -403,7 +403,7 @@ private
 end
 </ruby>
 
-h4. Other ways to use filters
+h4. Other Ways to Use Filters
 
 While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
 
@@ -517,7 +517,7 @@ h3. The Request and Response Objects
 
 In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of +AbstractRequest+ and the +response+ method returns a response object representing what is going to be sent back to the client.
 
-h4. The +request+ object
+h4. The +request+ Object
 
 The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html. Among the properties that you can access on this object are:
 
@@ -538,7 +538,7 @@ h5. +path_parameters+, +query_parameters+, and +request_parameters+
 
 Rails collects all of the parameters sent along with the request in the +params+ hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The +query_parameters+ hash contains parameters that were sent as part of the query string while the +request_parameters+ hash contains parameters sent as part of the post body. The +path_parameters+ hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
 
-h4. The response object
+h4. The +response+ Object
 
 The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
 
@@ -550,7 +550,7 @@ The response object is not usually used directly, but is built up during the exe
 |charset|The character set being used for the response. Default is "utf-8".|
 |headers|Headers used for the response.|
 
-h5. Setting custom headers
+h5. Setting Custom Headers
 
 If you want to set custom headers for a response then +response.headers+ is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to +response.headers+ this way:
 
@@ -565,7 +565,7 @@ Rails comes with two built-in HTTP authentication mechanisms:
 * Basic Authentication
 * Digest Authentication
 
-h4. HTTP basic authentication
+h4. HTTP Basic Authentication
 
 HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +authenticate_or_request_with_http_basic+.
 
@@ -587,7 +587,7 @@ end
 
 With this in place, you can create namespaced controllers that inherit from +AdminController+. The before filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
 
-h4. HTTP digest authentication
+h4. HTTP Digest Authentication
 
 HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
 
@@ -640,7 +640,7 @@ end
 
 The +download_pdf+ action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the +:disposition+ option to "inline". The opposite and default value for this option is "attachment".
 
-h4. Sending files
+h4. Sending Files
 
 If you want to send a file that already exists on disk, use the +send_file+ method.
 
@@ -662,7 +662,7 @@ WARNING: Be careful when using data coming from the client (params, cookies, etc
 
 TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the +:x_sendfile+ option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the +X-Sendfile+ header for this to work.
 
-h4. RESTful downloads
+h4. RESTful Downloads
 
 While +send_data+ works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the +show+ action, without any streaming:
 
@@ -712,7 +712,7 @@ Most likely your application is going to contain bugs or otherwise throw an exce
 
 Rails' default exception handling displays a "500 Server Error" message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
 
-h4. The default 500 and 404 templates
+h4. The Default 500 and 404 Templates
 
 By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the +public+ folder, in +404.html+ and +500.html+ respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
 
-- 
cgit v1.2.3


From a4b1ccec5c1df24c8f9a18c599575e7263624ac4 Mon Sep 17 00:00:00 2001
From: Xavier Noria <fxn@hashref.com>
Date: Sun, 15 Mar 2009 21:31:20 +0100
Subject: revised links in guides according to W3C link checker report

---
 railties/guides/source/action_controller_overview.textile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 3ce6720815..054ca99985 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -20,7 +20,7 @@ For most conventional RESTful applications, the controller will receive the requ
 
 A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
 
-NOTE: For more details on the routing process, see "Rails Routing from the Outside In":routing_outside_in.html.
+NOTE: For more details on the routing process, see "Rails Routing from the Outside In":routing.html.
 
 h3. Methods and Actions
 
-- 
cgit v1.2.3


From c9d7affd8c5da5326eeed9df86ea5b46dc02faa7 Mon Sep 17 00:00:00 2001
From: Joseph Pecoraro <joepeck02@gmail.com>
Date: Sat, 30 May 2009 00:49:25 -0400
Subject: Link titles are generally capitalized.

---
 railties/guides/source/action_controller_overview.textile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 054ca99985..e9eb07ea7b 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -41,7 +41,7 @@ def new
 end
 </ruby>
 
-The "Layouts & rendering guide":layouts_and_rendering.html explains this in more detail.
+The "Layouts & Rendering Guide":layouts_and_rendering.html explains this in more detail.
 
 +ApplicationController+ inherits from +ActionController::Base+, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
 
-- 
cgit v1.2.3


From 67317b6104fffeee2b51b77a1088ca8ef99f6d91 Mon Sep 17 00:00:00 2001
From: Pratik Naik <pratiknaik@gmail.com>
Date: Mon, 1 Jun 2009 09:41:46 +0100
Subject: Make ApplicationController extend from AC::Base

---
 .../source/action_controller_overview.textile      | 27 ++++++++++++++--------
 1 file changed, 17 insertions(+), 10 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index e9eb07ea7b..b131d0bf89 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -191,7 +191,7 @@ Session values are stored using key/value pairs like a hash:
 <ruby>
 class ApplicationController < ActionController::Base
 
-private
+  private
 
   # Finds the User with the ID stored in the session with the key
   # :current_user_id This is a common way to handle user login in
@@ -350,7 +350,8 @@ Before filters may halt the request cycle. A common before filter is one which r
 class ApplicationController < ActionController::Base
   before_filter :require_login
 
-private
+  private
+
   def require_login
     unless logged_in?
       flash[:error] = "You must be logged in to access this section"
@@ -390,10 +391,11 @@ Around filters are responsible for running the action, but they can choose not t
 <ruby>
 # Example taken from the Rails API filter documentation:
 # http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
-class ApplicationController < Application
+class ApplicationController < ActionController::Base
   around_filter :catch_exceptions
 
-private
+  private
+
   def catch_exceptions
     yield
   rescue => exception
@@ -575,7 +577,8 @@ class AdminController < ApplicationController
 
   before_filter :authenticate
 
-private
+  private
+
   def authenticate
     authenticate_or_request_with_http_basic do |username, password|
       username == USERNAME &&
@@ -597,7 +600,8 @@ class AdminController < ApplicationController
 
   before_filter :authenticate
 
-private
+  private
+
   def authenticate
     authenticate_or_request_with_http_digest do |username|
       USERS[username]
@@ -626,7 +630,7 @@ class ClientsController < ApplicationController
               :type => "application/pdf")
   end
 
-private
+  private
 
   def generate_pdf(client)
     Prawn::Document.new do
@@ -728,7 +732,8 @@ Here's how you can use +rescue_from+ to intercept all +ActiveRecord::RecordNotFo
 class ApplicationController < ActionController::Base
   rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
 
-private
+  private
+
   def record_not_found
     render :text => "404 Not Found", :status => 404
   end
@@ -741,7 +746,8 @@ Of course, this example is anything but elaborate and doesn't improve on the def
 class ApplicationController < ActionController::Base
   rescue_from User::NotAuthorized, :with => :user_not_authorized
 
-private
+  private
+
   def user_not_authorized
     flash[:error] = "You don't have access to this section."
     redirect_to :back
@@ -757,7 +763,8 @@ class ClientsController < ApplicationController
     @client = Client.find(params[:id])
   end
 
-private
+  private
+
   # If the user is not authorized, just throw the exception.
   def check_authorization
     raise User::NotAuthorized unless current_user.admin?
-- 
cgit v1.2.3


From c2917940f5997e824263d89f2bac7a0297fc6935 Mon Sep 17 00:00:00 2001
From: Joseph Pecoraro <joepeck02@gmail.com>
Date: Mon, 1 Jun 2009 09:42:59 -0400
Subject: Fixed XHR typo and another Application => ApplicationController typo

---
 railties/guides/source/action_controller_overview.textile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index b131d0bf89..756caea5fe 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -375,7 +375,7 @@ The method simply stores an error message in the flash and redirects to the logi
 In this example the filter is added to +ApplicationController+ and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with +skip_before_filter+:
 
 <ruby>
-class LoginsController < Application
+class LoginsController < ApplicationController
   skip_before_filter :require_login, :only => [:new, :create]
 end
 </ruby>
@@ -444,7 +444,7 @@ The Rails API documentation has "more information on using filters":http://api.r
 
 h3. Verification
 
-Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHTTPRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
+Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHttpRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
 
 Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
 
-- 
cgit v1.2.3


From f4571e3617ccd9cc9e5ee9f7431066bd80395e22 Mon Sep 17 00:00:00 2001
From: orangea <adrian.bloomer@gmail.com>
Date: Sat, 23 Jan 2010 09:20:46 -0800
Subject: generate_pdf gets it's parameter now

---
 railties/guides/source/action_controller_overview.textile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'railties/guides/source/action_controller_overview.textile')

diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 46a28da8c4..bedca59c12 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -625,9 +625,9 @@ class ClientsController < ApplicationController
   # returns it. The user will get the PDF as a file download.
   def download_pdf
     client = Client.find(params[:id])
-    send_data(generate_pdf, 
+    send_data generate_pdf(client), 
               :filename => "#{client.name}.pdf",
-              :type => "application/pdf")
+              :type => "application/pdf"
   end
 
   private
-- 
cgit v1.2.3

