Last active
December 28, 2015 02:22
-
-
Save jponc/6de83240b084656061b9 to your computer and use it in GitHub Desktop.
Service Object Example
This file contains hidden or 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 Invoice | |
def process_payment | |
# In this manner, it abstracts the logic of payment processing to the service object | |
InvoiceServices::Payment.new(self).process | |
end | |
end | |
class Tracker | |
def self.track | |
# Do tracking stuff here | |
end | |
end | |
class Email | |
def invoice_paid_mail(invoice) | |
# Send email here | |
end | |
end | |
# As you can see, this service object gives you all the business related logic. | |
# It generates a Stripe charge, it creates the analytics record and sends the email | |
# This code below should not be placed to a model since it is business related | |
class InvoiceServices::Payment | |
def initialize(invoice) | |
@invoice = invoice | |
end | |
def process | |
pay_stripe | |
record_analytics | |
send_email | |
end | |
def pay_stripe | |
Stripe.create_charge(@invoice) | |
end | |
def record_analytics | |
Tracker.track('invoice paid!') | |
end | |
def send_email | |
Email.invoice_paid_mail(@invoice) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment