Last active
December 18, 2015 22:39
-
-
Save jcamenisch/5855761 to your computer and use it in GitHub Desktop.
A simple currency class
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 Currency | |
def initialize(value) | |
@value = (value || 0).to_d.round(2) | |
end | |
attr_reader :value | |
alias_method :to_d, :value | |
def to_currency; self; end | |
alias_method :dollars, :to_currency | |
def method_missing(method, *args, &blk) | |
ret = @value.send(method, *args, &blk) | |
ret.is_a?(Numeric) ? Currency.new(ret) : ret | |
end | |
def eql?(other) | |
self.class.equal?(other.class) && @value == other.to_d | |
end | |
def ==(other) | |
@value == other.to_d | |
end | |
def <=>(other) | |
@value <=> other.to_d | |
end | |
def coerce(thing) | |
[thing.to_currency, @value] | |
end | |
def is_a?(klass) | |
super || @value.is_a?(klass) | |
end | |
alias_method :kind_of?, :is_a? | |
def to_str | |
sprintf("%0.2f", @value) | |
end | |
alias_method :to_s, :to_str | |
def inspect | |
"#<Currency:#{to_s}>" | |
end | |
end |
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 Object | |
def to_currency | |
Currency.new(self) | |
end | |
alias_method :dollars, :to_currency | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment