Skip to content

Instantly share code, notes, and snippets.

@mirrec
Created March 4, 2014 12:25
Show Gist options
  • Save mirrec/9345598 to your computer and use it in GitHub Desktop.
Save mirrec/9345598 to your computer and use it in GitHub Desktop.
Avoid callbacks hell, by creating service objects
class SeasonTicket < ActiveRecord::Base
# ...
def order!
self.price = calculate_price
self.status = :ordered
save!
self
end
# ...
end
class SeasonTicketMailer < ActionMailer::Base
def ordered_notification(ticket)
@ticket = ticket
mail :to => @ticket.player_email, :subject => t("mailers.season_ticket....")
end
end
class SeasonTicketOrderer
def initialize(ticket, notifiers = [])
@ticket = ticket
@notifiers = notifiers
end
def order!
@ticket.order!
@notifiers.each{ |notifier| notifier.notify(@ticket) }
end
end
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