Saturday, August 29, 2009

Action Caching

Recently, I have been working with RESTful web services. I came to a caching stage where I need to cache some requests that map to my actions. The problem is that I have actions with multiple possible routes, therefore those routes should be cached differently. For example:


/people/1?display=details
/people/1?display=summary
/people/1?display=details&format=xml
/people/1?display=summary&format=json


Fortunately, there is an option inside caches_action called :cache_path. All you need to do is to pass a proc object and return the path you want to cache. It is called with the current controller instance. In this case,

caches_action :index, :show, :cache_path => Proc.new { |c|
request_url = { :controller => c.params[:controller], :action => c.params[:action] }.merge(c.request.query_parameters)
c.url_for request_url
}


There is another problem when the request is coming without format, the cache returns the result with content-type: text/html. To solve this, add a before_filter inside application controller to assign the headers['Content-type'].


def set_default_response_format
response.headers['Content-type'] = 'application/xml; charset=utf-8' if params[:format].nil?
end

Saturday, August 22, 2009

MVC

Many Rails newcomers, even some people who know MVC quite well, often confuse how to code in the right way. The controller are usually fat, and the logic spreads across the whole application. The views still messy because it contains logic and even worse people often code like a controller (query to db). However, the model are usually skinny. I could say there is no restrictions in the way you code. It is a set of disciplines that every developers must know in order to have a cheaper maintenance.

MVC has been successful for many reasons, and some of those reasons are “readability”, “maintainability”, “modularity”, and “separation of concerns”. You’d like your code to have those properties, right? The rules of thumb are:

1. Controller should be skinny. This is what it means to have a controller know what to do without knowing the details of how to do it.
2. Any complexity related to building a business logic will be specified and implemented in the Model.
3. Inside View, access to instance variables that have been defined in Controller. Try not to use if-else condition or loop as much as possible.

By putting everything in the right place, you would benefit from a lot of MVC pattern.

Good example can be found on:
http://www.therailsway.com/2007/6/1/railsconf-recap-skinny-controllers
http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model

Subscribe in a Reader