May 10, 2010 Ingo Weiss
Resources have been a big topic in Rails ever since DHH’s keynote of 2006. All the more surprising I find the fact that four years later, the concept of resources in Rails is still largely limited to coding conventions materialized as generators (the scaffold and resource generators) and macros (such as the resource/s routing DSL methods) and conspicuously unavailable to code at runtime. A Rails application does not know what resources it exposes, for example, nor does a controller know which resource it is handling. If you want to take advantage of the predictable behavior of standard Rails resources and jump to the next level of abstraction (as we do in a current project), however, then this is exactly the kind of information you are likely to need.
In Rails the term ‘resource’ is most commonly used as representing the set of routes generated by the
resource/s routing DSL methods (We are really talking about a group of related REST resources when we talk about a resource in Rails). During the invocation of
resource/s in the Rails initialization sequence, instances of
ActionDispatch::Routing::Mapper::Resources::Resource are created representing the resource. Those instances are only used for route instantiation, however, and unlike the route instances themselves who are kept around and accessible at runtime via
Rails.application.routes, they are thrown away after the routes for the resource are instantiated.
What I would like to see happen is for the
ActionDispatch::Routing::Mapper::Resources::Resource class to be promoted to encapsulate all relevant information about a resource (not just what’s needed for route instantiation), and it’s instances to be kept around and be accessible at
Rails.application.resources. I plan to write a patch to that effect, but needed the functionality now so I wrote the resource_awareness gem as a short-term fix. The gem makes information about the resources defined via
resource/s available at
Rails.application.resources, as a collection of
Rails::Resource instances (please see the README for more information about their attributes). It also gives controllers a
resource method returning the resource they are handling, if any.
I believe that making this information available to code at runtime opens the door for interesting new abstractions, and I hope to write about some in further posts.blog comments powered by Disqus