Class: Konvert::Money

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Operations

#*, #+, #-, #/, #<, #==, #>, #add, #perform_sum, #subtract

Constructor Details

#initialize(amount, currency) ⇒ Money

Returns a new instance of Money.



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

def initialize(amount, currency)
  @amount = amount
  @currency = currency
end

Instance Attribute Details

#amountObject

Returns the value of attribute amount.



7
8
9
# File 'lib/money.rb', line 7

def amount
  @amount
end

#currencyObject

Returns the value of attribute currency.



8
9
10
# File 'lib/money.rb', line 8

def currency
  @currency
end

Class Method Details

.base_currencyObject



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

def self.base_currency
  @@base_currency
end

.conversion_rates(base, currency_hash) ⇒ Object



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

def self.conversion_rates(base,currency_hash)
  @@base_currency = base
  @@currency_hash = currency_hash
end

.currency_hashObject



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

def self.currency_hash
  @@currency_hash
end

Instance Method Details

#conversion_rates_set?Boolean

Returns:

  • (Boolean)


48
49
50
51
52
53
54
55
56
# File 'lib/money.rb', line 48

def conversion_rates_set?
  if (defined?(@@base_currency)).nil? || (defined?(@@currency_hash)).nil?
    p "Conversion rates not set: Please set conversion rates first."
    exit(false)
    #abort 'Conversion rates not set: Please set conversion rates first.'
  else
    true
  end
end

#convert_to(to_currency) ⇒ Object



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

def convert_to(to_currency)
  return unless (conversion_rates_set? && currency_defined?)
  if to_currency == Money.base_currency
    amount =  self.convert_to_base_amount
  else
    amount_in_base = self.convert_to_base_amount
    amount = amount_in_base * Money.currency_hash[to_currency]
  end
  Money.new(amount, to_currency)
end

#convert_to_base_amountObject



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

def convert_to_base_amount
  return unless (conversion_rates_set? && currency_defined?)
  self.currency == Money.base_currency ? self.amount : self.amount /  Money.currency_hash[self.currency]
end

#currency_defined?Boolean

Returns:

  • (Boolean)


57
58
59
60
61
62
63
64
65
# File 'lib/money.rb', line 57

def currency_defined?
  unless (@@currency_hash.key?(self.currency) || self.currency == @@base_currency)
    p "Invalid currency: Rates for #{self.currency} not defined in currency hash"
    exit(false)
    #abort "Invalid currency: Rates for #{self.currency} not defined in currency hash"
  else
    true
  end
end

#inspectObject



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

def inspect
  p sprintf('%.2f', amount) + ' ' + currency
end