Skip to content

Instantly share code, notes, and snippets.

@jcamenisch
Last active December 18, 2015 22:39
Show Gist options
  • Save jcamenisch/5855761 to your computer and use it in GitHub Desktop.
Save jcamenisch/5855761 to your computer and use it in GitHub Desktop.
A simple currency class
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
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