=========================================
Creating a Global REST Controller
Let’s imagine that you have an application that houses close to 400
controllers. Each of these controllers accesses a specific model that
contains normalized data. While there are a lot of tricks you can
perform for normalization, let’s assume that after you further normalize
and consolidate databases you still have 300 controllers left over.
Of these 300 controllers, half of them are composed of normal REST
methods, and the other half are comprised of normal REST methods and
special methods which perform specific actions.
This means that each of those controllers at a bare minimum could have
close to 80 lines of code.
Everyone talks about thin controllers. I’m going to show you a way to
create a Global REST controller that will make most if not all of your
controllers very thin.
Take a look at the code above and look closely at the Global REST
Controller.
Let’s pretend that you have a controller that manages pages, ie. a Pages
Controller. It’s comprised of only index, new, edit, show, create,
update, and destroy. No other actions.
By implementing a Global REST controller, you could place this in your
pages controller:
class PagesController < GlobalRestController
end
… and that’s all you need (2 lines of code)
In your index.html.erb view you would replace one instance variable
@pages with @objects and you are done.
Now then, going back to the old scenario I posted above, you could
effectively take 150 controllers with say 78 lines of code and reduce
11,700 lines of code down to … 300.
What could you do with your other 150 controllers?
class SomeOtherController < GlobalRestController
def some_custom_action
… etc.
… etc.
end
def some_other_custom_action
… etc.
… etc.
end
end
Your custom actions would be listed but you would automatically inherit
the other 7 rest methods automatically. No extra code needed.
What if you want to overwrite one of the REST methods with a custom REST
method of your own?
class SomeOtherController < GlobalRestController
def index
@pages = Page.find(:all, :conditions => ‘parent_id IS NOT NULL’)
respond_to do |format|
format.html
format.xml { render :xml => @pages }
end
end
end
You just simply place the REST method into your controller and it still
picks up the other 6 REST methods. You then keep the index.html.erb
page intact without @objects changes and you are done.
How well does this work?
I currently run a football statistics site that houses 75 controllers
and (66 of them) are part of a Global REST Controller mechanism. I have
had no issues whatsoever using it.
I hope this tutorial helps someone out. If you liked this tutorial, you
can check out a very lengthy tutorial I wrote yesterday on mailers and
observers here:
http://www.ruby-forum.com/topic/202316
Take care.