A Brief Introduction to Decent Exposure

A helper for creating declarative interfaces in Rails controllers

Doug Alcorn, doug@gaslight.co

Scaffolding


class EmployeesController < ApplicationController
  before_filter :get_company                            

  def index
    @employees = @company.employees.all
  end

  private

  def get_company
    @company = Company.find(params[:company_id])
  end
end
    

Instance Variables in Views


Hi, <%= @employee.name %>
    
In object-oriented programming, an object uses instance variables to store private information. If you want to access an object’s instance variables, those variables should only be accessible through instance methods. At least, this is the expectation.

Declarative Helper Methods


class EmployeesController < ApplicationController

  helper_method :employees, :company

  def index; end

  protected

  def company
    @company ||= Company.find(params[:company_id])
  end

  def employees
    @employees ||= company.employees.all
  end
end      
    

Trickier Example


def employee
  @employee ||= if params[:id]
    Employee.find params[:id]
  else
    Employee.new params[:employee]
  end
end
    

Decent Exposure


class EmployeesController < ApplicationController
  expose(:company)
  expose(:employees) { company.employees.all }
  expose(:employee)
end
    

More Info