Created
May 28, 2018 20:38
-
-
Save Mardiniii/19b242e8ee5ed26838c241ef8856c881 to your computer and use it in GitHub Desktop.
Single Responsability Principle: A class should have one and only one reason to change, meaning that a class should have only one job.
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
# Violates SRP | |
class Invoice | |
def initialize(items, client) | |
@items = items | |
@client = client | |
@total = 0 | |
end | |
def generate | |
@total = @items.inject(0) { |sum, i| sum + i } | |
end | |
def send_email | |
Mailer.deliver( | |
from: '[email protected]', | |
to: @client.email, | |
subject: 'Your new invoice was created!', | |
invoice: self | |
) | |
end | |
end | |
# Enforces SRP | |
class InvoiceGenerator | |
def initialize(items, client) | |
@items = items | |
@client = client | |
@total = 0 | |
end | |
def generate | |
@total = @items.inject(0) { |sum, item| sum + item.price } | |
self.save | |
end | |
end | |
class InvoiceMailer | |
def initialize(invoice) | |
@invoice = invoice | |
end | |
def send_email | |
Mailer.deliver( | |
from: '[email protected]', | |
to: @client.email, | |
subject: 'Your new invoice was created!', | |
invoice: @invoice | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment