I have been using modules with my controllers. If you are following RESTful Rails application development you might end up with lots of skinny controllers. One way of logically grouping your controllers is to use modules.
script/generate controller mymodule/mycontroller
does this for you. But what about routes? In your routes.rb file you would then setup something like the following.
map.with_options :path_prefix => 'mymodule',
:name_prefix => 'mymodule_' do |mymodule|
[ :allofmy, :restful, :controllers, :here ].each do |controller|
mymodule.resources controller, :controller => "mymodule/#{controller}"
end
end
Now you have a bunch of skinny restful controllers grouped logically together, routes that are module/namespace aware and url_for that works anywhere in the application using the name_prefix specified ( ie, redirect_to mymodule_myresource_url ).
Here’s another example of controllers in a module with nested resources
map.resources :owner,
:controller => 'akc/owner',
:path_prefix => 'akc',
:name_prefix => 'akc_' do |owner|
owner.resources :pet, :controller => "akc/pet"
end
While this is not usually necessary for small applications, it is useful when you have a application with different views on the same model with widely differing behavior. For example you might have 3 different views of a User model. One would be the admin view as seen by the administrator with it’s own layouts and page flow. Another might be the publicly available view of the User with updates allowed by the User if they are authenticated. Another might be XML over REST but secured by SSL X509 client certificates. Now you could do these all in one controller but why? It would be messy.
Using multiple namespaced modules for your controllers let’s you slap different views and web behavior on one model. It also forces you put your business logic and model behavior in the model too and not in the controller or view where it doesn’t belong. It puts the VC back in Rails MVC and you can still do RESTful routes.
Posted on June 27th, 2007 by dysinger
Filed under: Uncategorized