Created
July 6, 2012 17:29
-
-
Save gma/3061489 to your computer and use it in GitHub Desktop.
Exceptions and the observer pattern
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 | |
include Publisher | |
def create(iteration, attributes) | |
card = iteration.cards.build(attributes) | |
card.save! | |
rescue ActiveRecord::RecordInvalid | |
notify_subscribers(:create_failed, card) | |
else | |
notify_subscribers(:created, 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 CardPersistenceResponder < Struct.new(:controller) | |
def created(card) | |
controller.instance_eval do | |
redirect_to planning_path(card.project) | |
end | |
end | |
def create_failed(card) | |
controller.instance_eval do | |
@title = 'New card' | |
@card = card | |
flash.now[:alert] = 'Your card needs a title' | |
render :action => 'new' | |
end | |
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 | |
creator = CardCreator.new | |
creator.add_subscriber(CardPersistenceResponder.new(self)) | |
creator.create(project.backlog, card_params) | |
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
module Publisher | |
def add_subscriber(object) | |
@subscribers ||= [] | |
@subscribers << object | |
end | |
def notify_subscribers(message, *args) | |
return if @subscribers.blank? | |
@subscribers.each do |subscriber| | |
subscriber.send(message, *args) if subscriber.respond_to?(message) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since I made this gist I've written the process up: http://theagileplanner.com/blog/building-agile-planner/refactoring-with-hexagonal-rails