Created
September 19, 2016 16:24
-
-
Save aliibrahim/a7965687ca8f7d028dad14a8b6856a0e to your computer and use it in GitHub Desktop.
Refactored version of receipt printer
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 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