Class: CurrencyManager::Money

Inherits:
Object
  • Object
show all
Defined in:
lib/currency_manager/money.rb

Constant Summary collapse

@@rates =
{}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(amount, currency) ⇒ Money

Returns a new instance of Money.

Raises:

  • (ArgumentError)


5
6
7
8
9
10
# File 'lib/currency_manager/money.rb', line 5

def initialize(amount, currency)
  raise ArgumentError, 'currency rate is not a Number' unless amount.is_a? Numeric
  raise ArgumentError, 'currency name is not a String' unless currency.is_a? String
  @amount = amount
  @currency = currency
end

Class Method Details

.conversion_rates(currency, rates = {}) ⇒ Object

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/currency_manager/money.rb', line 12

def self.conversion_rates(currency, rates = {})
  raise ArgumentError, 'base currency key is not a String' unless currency.is_a? String
  raise ArgumentError, 'base currency rates is not a Hash' unless rates.is_a? Hash
  @@rates = {}

  rates.each do |key, value|
    unless key.is_a? String
      @@rates = {}
      raise ArgumentError, 'currency key is not a String'
    end

    unless value.is_a? Numeric
      @@rates = {}
      raise ArgumentError, "currency '#{key}' rate is not a Number"
    end

    @@rates[key.downcase] = value
  end

  @@base_currency = currency.downcase
  @@rates[@@base_currency] = 1
  true
end

Instance Method Details

#==(money) ⇒ Object



78
79
80
81
82
# File 'lib/currency_manager/money.rb', line 78

def ==(money)
    return false unless money.is_a?(self.class)
    new_amount = convert_amount(money.amount, money.currency, @currency)
    @amount.round(2) == new_amount.round(2)
end

#amountObject



36
37
38
# File 'lib/currency_manager/money.rb', line 36

def amount
  @amount
end

#convert_to(new_currency) ⇒ Object



48
49
50
51
# File 'lib/currency_manager/money.rb', line 48

def convert_to(new_currency)
  new_amount = convert_amount(@amount, @currency, new_currency)
  self.class.new(new_amount, new_currency)
end

#currencyObject



40
41
42
# File 'lib/currency_manager/money.rb', line 40

def currency
  @currency
end

#inspectObject



44
45
46
# File 'lib/currency_manager/money.rb', line 44

def inspect
  '%.2f ' %  @amount + @currency
end