Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jsuchal/8720090 to your computer and use it in GitHub Desktop.
Save jsuchal/8720090 to your computer and use it in GitHub Desktop.
bus = On::Bus.new.
subscribe(DonationReceipt).
subscribe(NotifyAccountingSystem).
subscribe(UpdatePublicStats).
subscribe(LogInternalMetrics).
subscribe(UpdateAnalyticsDashboard).
subscribe(RealtimeViewerUpdate)
class DonationsController # < ActionController::Base
def create
listener = bus.
on(:donation_created) {|donation| send_user_to_payment_gateway(donation) }.
on(:donation_invalid) {|donation| render donation.errors, status: :bad_request }
# or
listener = bus.on(
donation_created: ->(donation) { send_user_to_payment_gateway(donation) },
donation_invalid: ->(donation) { render donation.errors, status: :bad_request }
)
DonationService.new.add_donation(current_user, params[:donation], listener)
end
private
def send_user_to_payment_gateway(donation)
#...
end
end
class DonationService
def initialize(options={})
@donation_class = options.fetch(:donation_class) { Donation }
end
def add_donation(donor, donation_attributes, listener)
donation = @donation_class.new(donation_attributes.merge(donor: donor))
if donation.valid?
donation.save!
listener.donation_created(donation)
else
listener.donation_invalid(donation)
end
end
end
class DonationReceipt
def donation_created(donation)
Mailer.delay.send_donation_receipt(donation)
end
end
class NotifyAccountingSystem
def donation_created(donation)
#..
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment