Created
July 6, 2012 10:46
-
-
Save gma/3059469 to your computer and use it in GitHub Desktop.
Moving model creation/update to a separate class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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