After reading a great article on Sandi Metz' rules for developers. I thought I'd do a generalized example on the Facade Pattern that was used to solve the "Only instantiate one object in the controller" rule.
The goal of the Facade Pattern is to provide a unified interface to a set of interfaces in a subsystem. This means you'd just have some object that can send back other objects. You would typically have something like this in a controller:
class ObjectsController < ApplicationController before_filter :load_other_needed_objects, :only => [:index] def index @objects = Object.all end def load_other_needed_objects @other_needed_objects = OtherObject.all end end
Using the Facade Pattern you simply create an object interface that can access all of these objects.
class ObjectInterface attr_reader :objects def initialize(objects) @objects = objects end def other_needed_objects @other_needed_objects = OtherObjects.all end end
And now the updated controller:
class ObjectsController < ApplicationController def index @interface = ObjectInterface.new(Object.all) end end
Now we're programming! :-)
David Chapman is a Ruby on Rails developer at isotope|eleven with over 5 years development experience. He's currently majoring in Electrical Engineering with a minor in Computer Science at the University of Alabama at Birmingham. David is a Linux geek, a math geek, a physics geek, a serious gamer, and a reader of Reddit. His super power is eating chips and salsa.