Skip to content

Instantly share code, notes, and snippets.

@Mardiniii
Created May 28, 2018 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mardiniii/19b242e8ee5ed26838c241ef8856c881 to your computer and use it in GitHub Desktop.
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.
# 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: 'my_solid_company@email.com',
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: 'my_solid_company@email.com',
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