Last active
January 4, 2016 11:16
-
-
Save rob-murray/577c6bf2ae8d5abee1cd to your computer and use it in GitHub Desktop.
example money class in Ruby (GBP)
This file contains 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 Money | |
STANDARD_VAT_RATE = 0.2.freeze | |
attr_reader :amount | |
def self.in_pence(amount_in_pence) | |
new(amount_in_pence) | |
end | |
def initialize(amount) | |
@amount = amount.to_int | |
freeze | |
end | |
def to_currency | |
amount / 100.0 | |
end | |
def to_s | |
"£%.2f" % to_currency | |
end | |
def to_int | |
amount | |
end | |
def to_i | |
amount | |
end | |
def negative? | |
amount < 0 | |
end | |
def positive? | |
amount > 0 | |
end | |
def zero? | |
amount.zero? | |
end | |
def ==(other_money) | |
self.class == other_money.class && | |
amount == other_money.amount | |
end | |
alias :eql? :== | |
def +(value) | |
self.class.new(amount + value.to_int) | |
end | |
def vat_of(vat_rate = STANDARD_VAT_RATE) | |
self.class.new to_vat(vat_rate) | |
end | |
private | |
def to_vat(vat_rate) | |
(amount * vat_rate).round | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment