Class: CurrencyShushugah::Money

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/currency_shushugah.rb

Overview

Understands currency and quantity

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(quantity, currency) ⇒ Money

Returns a new instance of Money.



16
17
18
19
20
# File 'lib/currency_shushugah.rb', line 16

def initialize(quantity, currency)
  raise UnsupportedCurrency unless rates[currency]
  @quantity = quantity
  @currency = currency
end

Class Method Details

.conversion_rates(base_currency, hash_rates) ⇒ Object



12
13
14
# File 'lib/currency_shushugah.rb', line 12

def self.conversion_rates(base_currency, hash_rates)
  @rates = hash_rates.merge(base_currency => 1)
end

.ratesObject



67
68
69
# File 'lib/currency_shushugah.rb', line 67

def self.rates
  Money.instance_variable_get(:@rates)
end

Instance Method Details

#*(other) ⇒ Object



54
55
56
# File 'lib/currency_shushugah.rb', line 54

def *(other)
  new_money(quantity * other)
end

#+(other) ⇒ Object



38
39
40
# File 'lib/currency_shushugah.rb', line 38

def +(other)
  new_money(quantity + other.convert_to(currency).quantity)
end

#-(other) ⇒ Object



42
43
44
# File 'lib/currency_shushugah.rb', line 42

def -(other)
  self + -other
end

#-@Object



46
47
48
# File 'lib/currency_shushugah.rb', line 46

def -@
  new_money(-quantity)
end

#/(other) ⇒ Object

Raises:



58
59
60
61
# File 'lib/currency_shushugah.rb', line 58

def /(other)
  raise DivisionByZero if other.zero?
  self * (1.0 / other)
end

#<=>(other) ⇒ Object



22
23
24
25
# File 'lib/currency_shushugah.rb', line 22

def <=>(other)
  return unless other.class == self.class
  quantity <=> other.convert_to(currency).quantity
end

#coerce(other) ⇒ Object



50
51
52
# File 'lib/currency_shushugah.rb', line 50

def coerce(other)
  [self, other]
end

#convert_to(other_currency) ⇒ Object



31
32
33
34
35
36
# File 'lib/currency_shushugah.rb', line 31

def convert_to(other_currency)
  raise UnsupportedCurrency unless rates[other_currency]
  return self if currency == other_currency
  new_quantity = @quantity * rates[other_currency] / rates[currency]
  new_money(new_quantity, other_currency)
end

#inspectObject



27
28
29
# File 'lib/currency_shushugah.rb', line 27

def inspect
  "#{'%0.2f' % quantity} #{currency}"
end

#new_money(quantity, currency = @currency) ⇒ Object



63
64
65
# File 'lib/currency_shushugah.rb', line 63

def new_money(quantity, currency = @currency)
  Money.send :new, quantity.round(2), currency
end