Skip to content

Instantly share code, notes, and snippets.

@aliibrahim
Created September 19, 2016 16:24
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 aliibrahim/a7965687ca8f7d028dad14a8b6856a0e to your computer and use it in GitHub Desktop.
Save aliibrahim/a7965687ca8f7d028dad14a8b6856a0e to your computer and use it in GitHub Desktop.
Refactored version of receipt printer
class ReceiptPrinter
attr_reader :output, :items
COST = {
'meat' => 5,
'milk' => 3,
'candy' => 1,
}
TAX = 0.05
def initialize(output: $stdout, items:)
@output = output
@items = items
end
def print
subtotal = sum_of_items(items)
items.each do |item|
item_cost = COST[item]
output_item(item, item_cost)
end
output.puts divider
output_item("subtotal", subtotal)
taxes = calculate_taxes(subtotal)
output_item("tax", taxes)
output.puts divider
output_item("total", receipt_total(subtotal, taxes))
end
private
def divider
'-' * 13
end
def output_item(name, value)
output.puts "#{name}: #{sprintf('$%.2f', value)}"
end
def calculate_taxes(amount)
amount * TAX
end
def receipt_total(subtotal, taxes)
subtotal + taxes
end
def sum_of_items(items)
subtotal = items.reduce(0) do |sum, item|
item_cost = COST[item]
sum + item_cost.to_i
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment