Module: Monee::Arithmetic
- Included in:
- Money
- Defined in:
- lib/monee/arithmetic.rb
Overview
modularizing the arithmetic related methods in a separate module for money
Instance Method Summary collapse
-
#choose_operand(operator, operand) ⇒ Numeric
convert to cents if add or subtract dont convert to cents if multiply or divide.
-
#coerce(other) ⇒ Object
this method is to support the order of the operation 2 * Monee::Money.new(50, ‘EUR’).
-
#operator ⇒ Money
metaprogramming way of defining methods.
Instance Method Details
#choose_operand(operator, operand) ⇒ Numeric
convert to cents if add or subtract dont convert to cents if multiply or divide
32 33 34 35 36 37 38 |
# File 'lib/monee/arithmetic.rb', line 32 def choose_operand(operator, operand) if %i[+ -].include?(operator) operand.to_cents elsif %i[* /].include?(operator) operand end end |
#coerce(other) ⇒ Object
this method is to support the order of the operation 2 * Monee::Money.new(50, ‘EUR’)
42 43 44 |
# File 'lib/monee/arithmetic.rb', line 42 def coerce(other) return self, other end |
#operator ⇒ Money
metaprogramming way of defining methods
overloads the operators with 2 operands adds amount/cents if number converts to the currency and calculates if money object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/monee/arithmetic.rb', line 10 %i[+ - * /].each do |operator| define_method(operator) do |operand| result_cents = case operand when ::Numeric cents.send(operator, choose_operand(operator, operand)) when klass cents.send(operator, operand.convert_to_cents(currency)) else raise InvalidOperand end amount = result_cents.to_amount klass.new(amount, currency) end end |