Skip to content

Instantly share code, notes, and snippets.

@DimaSamodurov
Created September 19, 2019 08:21
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 DimaSamodurov/f8b9ada3df0753bbba8f3d00bf931b40 to your computer and use it in GitHub Desktop.
Save DimaSamodurov/f8b9ada3df0753bbba8f3d00bf931b40 to your computer and use it in GitHub Desktop.
class Receipt
def initialize(user:)
@user = user
end
def payments
# Imagine you get payments like Payment.where(user: @user). So payments are actually retrieved, `get`.
[
{name: 'Shoes', price: 5.2 },
{name: 'Book', price: 3.5 }
]
end
def total
payments.inject(0) { |sum, p| sum + p[:price] }
end
end
user = 'Dima'
receipt = Receipt.new(user: user)
puts "Hey #{user}! Thank you for the payment of #{receipt.total}. Your receipt below.."
# Bad name. Here we don't pay attention to action. We don't care of how it is generated. We describe the thing. The Receipt.
class GenerateReceipt
def initialize(user:)
@user = user
end
def get_payments
# Imagine you get payments like Payment.where(user: @user). So payments are actually retrieved, `get`.
[
{name: 'Shoes', price: 5.2 },
{name: 'Book', price: 3.5 }
]
end
# this looks ugly. When you think about a 'total', why do you need to think about it like 'get_total'?
def get_total
get_payments.inject(0) { |sum, p| sum + p[:price] }
end
end
user = 'Dima'
receipt = GenerateReceipt.new(user: user)
puts "Hey #{user}! Thank you for the payment of #{receipt.get_total}. Your receipt below.."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment