Skip to content

Instantly share code, notes, and snippets.

@gma
Created July 6, 2012 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gma/3059469 to your computer and use it in GitHub Desktop.
Save gma/3059469 to your computer and use it in GitHub Desktop.
Moving model creation/update to a separate class
class CardCreator < Struct.new(:listener)
class Failed < RuntimeError
attr_accessor :model
def initialize(model)
@model = model
end
end
def self.create(iteration, attributes)
card = iteration.cards.build(attributes)
card.save!
rescue ActiveRecord::RecordInvalid
raise Failed.new(card)
else
card
end
end
class CardsController < ApplicationController
def create
card = CardCreator.create(project.backlog, card_params)
redirect_to planning_path(card.iteration.project)
rescue CardCreator::Failed => e
@card = e.model
@title = 'New card'
flash.now[:alert] = 'Your card needs a title'
render :action => 'new'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment