Skip to content

Instantly share code, notes, and snippets.

@fnando
Created September 2, 2012 14:25
Show Gist options
  • Save fnando/3599511 to your computer and use it in GitHub Desktop.
Save fnando/3599511 to your computer and use it in GitHub Desktop.
Just a refactored controller that uses a custom responder instead of those nasty respond_to blocks.
class NotesController < ApplicationController
self.responder = NotesResponder
def create
@page = Page.find(params[:page_id])
@note = page.notes.create(params[:note])
respond_with(@note, :location => page_path(@page))
end
end
class NotesResponder < ActionController::Responder
delegate :t, :flash, :to => :controller
def to_html
if resource.new_record?
flash[:notice] = t("fuck_yeah")
else
flash[:alert] = resource.errors.full_messages.to_sentence
end
redirect_to navigation_location
end
end
class NotesController < ApplicationController
def create
@page = Page.find(params[:page_id])
@note = page.notes.create(params[:note])
respond_to do |format|
format.html do
if @note.new_record?
flash[:notice] = t("fuck_yeah")
else
flash[:alert] = @note.errors.full_messages.to_sentence
end
redirect_to page_path(@page)
end
format.json
end
end
end
@tinogomes
Copy link

# Tenho simplificado o controller mais ainda, fazendo o uso do padrão Command;

class NotesController < ApplicationController
  self.responder = NotesResponder

  def create
    @notes, @page = CreateNoteForPage.process!(params)

    respond_with(@note, :location => page_path(@page))
  end
end

class CreateNoteForPage
  def initialize(page_id, note_attributes)
    @page = Page.find(page_id)
    @note = @page.notes.create(note_attributes)
  end

  def process!
    {
      :page => @page,
      :note => @note
    }
  end

  def self.process!!(params)
    new(params[:page_id], params[:note]).process!
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment