Created
July 6, 2012 17:00
-
-
Save gma/3061327 to your computer and use it in GitHub Desktop.
Moving response callbacks out of controller
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) | |
def create(iteration, attributes) | |
card = iteration.cards.build(attributes) | |
if card.save | |
listener.created(card) | |
else | |
listener.create_failed(card) | |
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 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(CardPersistenceResponder.new(self)) | |
creator.create(project.backlog, card_params) | |
end | |
end |
Since I made this gist I've written the process up: http://theagileplanner.com/blog/building-agile-planner/refactoring-with-hexagonal-rails
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Riccieri – Nice use of the stabby lambda. It clearly bothered Steve Tooke a bit too; have a look at how he tweaked it:
https://gist.github.com/3062683
The SimpleDelegator is how I'm now doing it, and I've moved the responder class inside the controller (so it's just called PersistenceResponder). I prefer it because I'd rather use the observer pattern than explicit callbacks (it feels slightly more decopuled). I'll blog the finished result and link to it here…