Created
March 4, 2014 12:25
-
-
Save mirrec/9345598 to your computer and use it in GitHub Desktop.
Avoid callbacks hell, by creating service objects
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 SeasonTicket < ActiveRecord::Base | |
# ... | |
def order! | |
self.price = calculate_price | |
self.status = :ordered | |
save! | |
self | |
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 SeasonTicketMailer < ActionMailer::Base | |
def ordered_notification(ticket) | |
@ticket = ticket | |
mail :to => @ticket.player_email, :subject => t("mailers.season_ticket....") | |
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 SeasonTicketOrderer | |
def initialize(ticket, notifiers = []) | |
@ticket = ticket | |
@notifiers = notifiers | |
end | |
def order! | |
@ticket.order! | |
@notifiers.each{ |notifier| notifier.notify(@ticket) } | |
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 SeasonTicketsController < ApplicationController | |
# ... | |
def create | |
@season_ticket = SeasonTicket.new(params[:season_ticket]) | |
@season_ticket.player = current_customer | |
@notifiers = [ | |
MailerNotifier.new(SeasonTicketMailer, :ordered_notification) | |
] | |
if @season_ticket.valid? | |
SeasonTicketOrderer.new(@season_ticket, @notifiers).order! | |
notice_message | |
redirect_to wnm_core.profile_path | |
else | |
# ... | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment