Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

210 | Chapter 7: REST, Resources, and Web Services


One of the key points in the presentation was that resources can be more than things
we might think of as “objects”; examples given were relationships between objects,
events on objects, and object states. This is an important principle in REST. Rather
than adding another method#closeon aCaseobject, it may be more clear to factor
out aClosure object if more information about the closure needs to be persisted.


RESTful Routing


From the outside of an application, the most visible change in RESTful Rails is the new
routing. Classic Rails routing was based around the default route of/:controller
/:action/:id, with any extra parameters usually being carried in the query string.
This had advantages of simplicity and uniformity in routing, but it was brittle to
change. Refactoring actions from one controller to another required updating all
links pointing to that action; they had to be changed from:


link_to 'Close', :controller => 'cases', :action => 'close', :id => @case.id

to:


link_to 'Close', :controller => 'closures', :action => 'create',
:id => @case.id

The next major innovation in Rails routing was the prevalence of named routes. By
associating each URI with a name, you would get an easy way to refactor route URLs
without changing the inward links. This provided another layer of abstraction on top
of the actual URI parameters:


config/routes.rb
map.close_case '/cases/close/:id', :controller => 'cases', :action => 'close'


_case.rhtml
link_to 'Close', close_case_path(:id => @case.id)


Then, when the action moved, you could simply change the route without touching
the views:


map.close_case '/closures/create/:id', :controller => 'closures',
:action => 'create'

This greatly improved maintainability, but it increased verbosity. As there was
another layer of abstraction between URIs and actions, there was another file that
needed to be maintained, kept in sync with the rest of the code, and consulted when
tracing a request’s path through the application.


The biggest problem, however, was that these routes tended to be redundant and
overly numerous. The problem was not so much that there was one named route for
each URI, but that the URIs referred to actions on resources instead of resources.
The HTT Pphrase “GET /cases/show/1” is redundant. Both HTTPGETand theshow
action mean “give me this data.” According to RESTful principles, that phrase
should be “GET /cases/1,” where the HTT Pverb specifies the action and the URI
specifies the object of that action. Thus, Railsresource routing was born.

Free download pdf