Understanding Controllers in Ruby-on-Rails - Filtering and Verification, and Caching
(Page 3 of 4 )
3. Filtering and Verification
There are situations where certain processing must be done before a request is serviced. In such situations filters come into the picture. Filters are pieces of code that wrap the logic that needs to be called before or after any number of actions within the controller or its derived classes. There are two kinds of filters, before and after filters. The before filters work before a request has been processed, whereas the after filters do the task after the action has been invoked. For example, if a code for verifying a user's session must be called before invoking an action, the code would be:
def authorize
unless session[:user_id]
flash[:notice] ="Please log in"
redirect_to(:controller =>"login", :action =>"login")
end
end
class AdminController < ApplicationController
before_filter :authorize
# ...
Here the code to be executed before invoking any action within the AdminController is wrapped inside the authorize function, which is then called before any other action using the before_filter. The after_filter also works in the same way.
Filters can only call a code to be executed, but in situations where the need is to verify that a certain condition is met before an action is executed, filters can't do much. It is here that verification comes handy. Verification can be done by using the verify. Let's visualize a situation where the conditions are: the user-id must be valid, the user can only post comments, and if the conditions are met, redirect to the index page. The code using verify would be:
class BlogController < ApplicationController
verify :only => :post_comment,
:session => :user_id,
:add_flash => { :note =>"You must log in to comment"},
:redirect_to => :index
# ...
Its that easy.
4. Caching
Rendering the same content again and again puts a heavy load on the server. To counter such a case, caching is used. For example, an action render_one that is being called again and again would be a good candidate for caching. Indeed, caching is a requirement here.
In RoR caching can be done using the caching declaration. The caching can be page-level, action level, or both. To cache pages the declaration caches_page has to be used, and to cache actions the caches_action needs to be used. For example, in a blog management application, if the publicly viewable contents have to be cached the code would be:
class ContentController < ApplicationController
before_filter :verify_premium_user, :except => :public_content
caches_page :public_content
That ends the overview of the functionalities provided by the ActionController. In the near future I will discuss these in greater depth. But for now let's move on to the next section, which features an example of using the Controller for processing.
Next: Rails in the Real World >>
More Ruby-on-Rails Articles
More By APRajshekhar