Class: Geld::Money

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

Overview

Main class

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(amount, currency) ⇒ Money

Uses bigdecimal for safer money operations



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

def initialize(amount, currency)
  @amount = BigDecimal.new(amount.to_s)
  @currency = currency
end

Instance Attribute Details

#amountObject

Returns the value of attribute amount.



16
17
18
# File 'lib/geld.rb', line 16

def amount
  @amount
end

#currencyObject

Returns the value of attribute currency.



16
17
18
# File 'lib/geld.rb', line 16

def currency
  @currency
end

Class Method Details

.convertion_rates(currency, rates) ⇒ Object

Adds a converion rate in the configuration storage



25
26
27
28
# File 'lib/geld.rb', line 25

def self.convertion_rates(currency, rates)
  Geld.config ||= Config.new
  Geld.config.add_currency(currency, rates)
end

Instance Method Details

#!=(money) ⇒ Object

Tests equality



76
77
78
# File 'lib/geld.rb', line 76

def !=(money)
  compare(money, :!=)
end

#*(money) ⇒ Object

Multiplies two moneys



56
57
58
# File 'lib/geld.rb', line 56

def *(money)
  operate(money, :mult)
end

#+(money) ⇒ Object

Sums two moneys



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

def +(money)
  operate(money, :add)
end

#-(money) ⇒ Object

Subtracts two moneys



51
52
53
# File 'lib/geld.rb', line 51

def -(money)
  operate(money, :sub)
end

#/(money) ⇒ Object

Divides two moneys



61
62
63
# File 'lib/geld.rb', line 61

def /(money)
  operate(money, :div)
end

#<(money) ⇒ Object

Tests less than



86
87
88
# File 'lib/geld.rb', line 86

def <(money)
  compare(money, :<)
end

#==(money) ⇒ Object

Tests equality



71
72
73
# File 'lib/geld.rb', line 71

def ==(money)
  compare(money, :==)
end

#>(money) ⇒ Object

Tests greater than



81
82
83
# File 'lib/geld.rb', line 81

def >(money)
  compare(money, :>)
end

#convert_to(new_currency) ⇒ Object

Apply the specific rate or raises error if not found



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/geld.rb', line 31

def convert_to(new_currency)
  return dup if new_currency == self.currency

  new_amount = Geld.config &&
  Geld.config.get_rate(self.currency, new_currency) &&
  Geld.config.get_rate(self.currency, new_currency).mult(self.amount, 2)

  if new_amount.nil?
    raise Error::CurrencyNotFound.new("The desired currency is not set.")
  else
   Money.new(new_amount, new_currency)
  end
end

#inspectObject

Shows money formated



66
67
68
# File 'lib/geld.rb', line 66

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