decent_exposure
  Controladores sin @ivars



       Leo Soto M.
Controladores sin @ivars
Controladores sin @ivars
       ¿Por qué?
@ivars == estado dentro de una clase
@ivars en controladores == HACK
Problemas prácticos de los controladores
1. Duplicación
class PostsController
  def index
    @posts = Post.all
  end

  def create
    @post = Post.new(params[:post])
    @post.save
  end

  def new
    @post = Post.new
  end
def show
   @post = Post.find(params[:id])
 end

 def edit
   @post = Post.find(params[:id])
 end

 def update
   @post = Post.find(params[:id])
   @post.update_attributes(params[:post])
 end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy
  end
end
def show
   @post = Post.find(params[:id])
 end

 def edit
   @post = Post.find(params[:id])
 end

 def update
   @post = Post.find(params[:id])
   @post.update_attributes(params[:post])
 end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy
  end
end
2. ¿Qué variables puedo usar?
controlador.rb

def foo
  @x = ...
  @y = ...
  @z = ...
end

def bar
  @z = ...
end

def baz
  @x = ...
  @z = ...
end
foo.html.erb

...
<% render :partial => “some_partial” %>
...
baz.html.erb

...
<% render :partial => “some_partial” %>
...
_some_partial.html.erb

...
<div id=“BOOM”>
  <%= @y.to_s %>
</div>
...
¿Soluciones?
controlador.rb
before_filter :load_y
def load_y; @y = ... ; end

def foo
  @x = ...
  @z = ...
end

def bar
  @z = ...
end

def baz
  @x = ...
  @z = ...
end
controlador.rb
helper_method :y
def y; @y ||= ... ; end

def foo
  @x = ...
  @z = ...
end

def bar
  @z = ...
end

def baz
  @x = ...
  @z = ...
end
Introduciendo decent_exposure
controlador.rb
expose(:y) { ... }



def foo
  @x = ...
  @z = ...
end

def bar
  @z = ...
end

def baz
  @x = ...
  @z = ...
end
controlador.rb
expose(:y) { ... }
expose(:x) { ... }
expose(:z) { ... }
Un ejemplo real
class Admin::PromotionsController < AdminController
  expose(:promotions) { Promotion.all }
  expose(:promotion) do
    params[:id] ? Promotion.find(params[:id]) :
                  Promotion.new(params[:promotion])
  end

  def create
    if promotion.save
      redirect_to :action => :index
    else
      render :new
    end
  end
end
class Admin::PromotionsController < AdminController
  expose(:promotions) { Promotion.all }
  expose(:promotion)




  def create
    if promotion.save
      redirect_to :action => :index
    else
      render :new
    end
  end
end
https://github.com/voxdolo/decent_exposure

Decent exposure: Controladores sin @ivars