Class: VlatkoDawanda::Money

Inherits:
Object
  • Object
show all
Includes:
Comparable, Arithmetic
Defined in:
lib/vlatko_dawanda/money.rb

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Arithmetic

#coerce

Constructor Details

#initialize(amount, iso_code) ⇒ Money

Returns a new instance of Money.



19
20
21
22
# File 'lib/vlatko_dawanda/money.rb', line 19

def initialize(amount, iso_code)
  @amount = amount.to_d
  @currency = bank.find_currency(iso_code)
end

Class Attribute Details

.bankObject



10
11
12
# File 'lib/vlatko_dawanda/money.rb', line 10

def bank
  @bank ||= Bank.new
end

Class Method Details

.conversion_rates(base_currency, currencies) ⇒ Object



14
15
16
# File 'lib/vlatko_dawanda/money.rb', line 14

def conversion_rates(base_currency, currencies)
  bank.conversion_rates(base_currency, currencies)
end

Instance Method Details

#<=>(other) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/vlatko_dawanda/money.rb', line 46

def <=>(other)
  if currency == other.currency
    amount.to_d.round(2) <=> other.amount.to_d.round(2)
  else
    amount.to_d.round(2) <=> other.convert_to(currency).amount.to_d.round(2)
  end
end

#amountObject



24
25
26
# File 'lib/vlatko_dawanda/money.rb', line 24

def amount
  to_f_or_i(@amount)
end

#convert_to(currency) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/vlatko_dawanda/money.rb', line 36

def convert_to(currency)
  to_currency = bank.find_currency(currency)
  amount = if @currency == to_currency
    @amount
  else
    (@amount / @currency.rate) * to_currency.rate
  end
  self.class.new(amount, to_currency.iso_code)
end

#currencyObject



28
29
30
# File 'lib/vlatko_dawanda/money.rb', line 28

def currency
  @currency.iso_code
end

#inspectObject



32
33
34
# File 'lib/vlatko_dawanda/money.rb', line 32

def inspect
  "#{"%.2f" % amount} #{currency}"
end