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.

Generalization

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:

objects_controller.rb

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.

Observe:

object_interface.rb

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:

objects_controller.rb

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.