[uf-rest] Instance/Collection URL conventions

David Heinemeier Hansson david at loudthinking.com
Thu Nov 10 04:59:15 PST 2005


> Donald posted a lovely, concise recommendation (on rest-discuss)  
> about how to structure REST URLs which looks *remarkably* like what  
> Rails does (or will do, or maybe ought to do :-) by default.  He  
> gave me permission to share it here, and I've added it to the wiki:
>
> http://microformats.org/wiki/rest/urls

I like that. The only slight problem is how to automate the singular/ 
plural distinction. The current rules for a REST look are:

   map.connect  ':controller/:action', :action =>  
'index', :requirements => { :action => /[^\d]+/ }
   map.connect  ':controller/:id', :action => 'show', :requirements  
=> { :id => /[\d]+/ }
   map.connect  ':controller/:id/:action'

But that will either translate into widgets/ or widget/ -- not both.  
It would probably take a Routing patch to figure out a way to  
represent it all succinctly. Or, you could of course also just use  
the power of Ruby:

for entity in %( posts comments authors )
   map.send entity, "#{entity}/:action", :action =>  
'index', :requirements => { :action => /[^\d]+/ }
   map.send entity.singularize, "#{entity.singularize}/:id", :action  
=> 'show', :requirements => { :id => /[\d]+/ }
   map.send entity.singularize, "#{entity.singularize}/:id/:action"
end

And riddle me this, we could wrap it up in this extension:

Module RestRoutes
   def connect_entity(entity)
     entity = entity.to_s
     collection = entity.pluralize

     named_route(collection, "#{collection}/:action", :action =>  
'index', :requirements => { :action => /[^\d]+/ })
     named_route(entity , "#{entity}/:id", :controller =>  
collection, :action => 'show', :requirements => { :id => /[\d]+/ })
     named_route(entity , "#{entity}/:id/:action", :controller =>  
collection)
   end
end

ActionController::Routing::RouteSet.send :include, RestRoutes

...which would then allow you to do:

ActionController::Routing::Routes.draw do |map|
   map.connect_entity :post
   map.connect_entity :comments
end

I see the makings of a RESTifarian plugin shape up quickly ;)
--
David Heinemeier Hansson
http://www.37signals.com    -- Basecamp, Backpack, Writeboard, Tada
http://www.loudthinking.com -- Broadcasting Brain
http://www.rubyonrails.com  -- Web-application framework




More information about the microformats-rest mailing list