mirror of
https://github.com/maybe-finance/maybe.git
synced 2025-07-24 15:49:39 +02:00
Multi-currency support: Money + Currency class improvements (#553)
* Money improvements * Replace all old money usage
This commit is contained in:
parent
e5750d1a13
commit
fe2fa0eac1
43 changed files with 2982 additions and 196 deletions
62
lib/money/arithmetic.rb
Normal file
62
lib/money/arithmetic.rb
Normal file
|
@ -0,0 +1,62 @@
|
|||
module Money::Arithmetic
|
||||
CoercedNumeric = Struct.new(:value)
|
||||
|
||||
def +(other)
|
||||
if other.is_a?(Money)
|
||||
self.class.new(amount + other.amount, currency)
|
||||
else
|
||||
value = other.is_a?(CoercedNumeric) ? other.value : other
|
||||
self.class.new(amount + value, currency)
|
||||
end
|
||||
end
|
||||
|
||||
def -(other)
|
||||
if other.is_a?(Money)
|
||||
self.class.new(amount - other.amount, currency)
|
||||
else
|
||||
value = other.is_a?(CoercedNumeric) ? other.value : other
|
||||
self.class.new(amount - value, currency)
|
||||
end
|
||||
end
|
||||
|
||||
def -@
|
||||
self.class.new(-amount, currency)
|
||||
end
|
||||
|
||||
def *(other)
|
||||
raise TypeError, "Can't multiply Money by Money, use Numeric instead" if other.is_a?(self.class)
|
||||
value = other.is_a?(CoercedNumeric) ? other.value : other
|
||||
self.class.new(amount * value, currency)
|
||||
end
|
||||
|
||||
def /(other)
|
||||
if other.is_a?(self.class)
|
||||
amount / other.amount
|
||||
else
|
||||
raise TypeError, "can't divide Numeric by Money" if other.is_a?(CoercedNumeric)
|
||||
self.class.new(amount / other, currency)
|
||||
end
|
||||
end
|
||||
|
||||
def abs
|
||||
self.class.new(amount.abs, currency)
|
||||
end
|
||||
|
||||
def zero?
|
||||
amount.zero?
|
||||
end
|
||||
|
||||
def negative?
|
||||
amount.negative?
|
||||
end
|
||||
|
||||
def positive?
|
||||
amount.positive?
|
||||
end
|
||||
|
||||
# Override Ruby's coerce method so the order of operands doesn't matter
|
||||
# Wrap in Coerced so we can distinguish between Money and other types
|
||||
def coerce(other)
|
||||
[ self, CoercedNumeric.new(other) ]
|
||||
end
|
||||
end
|
Loading…
Add table
Add a link
Reference in a new issue