Thursday, February 22, 2007

still more rails

URL routing
An incoming URL always maps to some action within a controller. A controller is simply a Ruby class, and each action implemented by the controller is a public method within the controller class. The default mapping from URL to action method is (in "Rails-speak"):

/:controller/:action/:id

If the default URL routing does not meet your needs, you can easily specify your own routing rules, even using regular expressions

Rails routing rules are Ruby code. Here is an example:

map.connect 'date/:year/:month/:day',
:controller => 'blog',
:action => 'by_date',
:month => nil,
:day => nil,
:requirements => {:year => /\d{4}/,
:day => /\d{1,2}/,
:month => /\d{1,2}/}With this routing rule, the following URLs are valid:

http://myblog.com/date/2005
http://myblog.com/date/2005/08
http://myblog.com/date/2005/08/01

This rule decomposes a URL containing a date that, perhaps, a blog might use to display the postings for a particular date. A URL that matches this form will map to the BlogController class and the by_date method. The parameter hash will contain values for a four-digit year (/\d{4}/ is a Ruby regular expression), a two-digit month, and a two-digit day. Further, the month and day are optional; if no values are present, the parameter hash will contain the default value of nil.

Filters allow you to run preprocessing code before Rails executes an action and post-processing code after it completes an action. They are useful for such things as caching or authentication before calling the action, and compression or localization of the response after calling an action. The before_filter processing can either allow the action to be called normally by returning true, or abort the action by returning false (or by performing a render or redirect operation).





http://www.onlamp.com/pub/a/onlamp/2005/10/13/what_is_rails.html?page=5

No comments: