Class: Cash
- Inherits:
-
Object
show all
- Includes:
- Comparable, Equalable
- Defined in:
- lib/cash.rb,
lib/cash/currency.rb,
lib/cash/currency/iso4217.rb
Defined Under Namespace
Modules: Format
Classes: Currency
Instance Attribute Summary collapse
Instance Method Summary
collapse
Methods included from Equalable
#==, #hash
Constructor Details
#initialize(amount, currency) ⇒ Cash
Returns a new instance of Cash.
12
13
14
|
# File 'lib/cash.rb', line 12
def initialize(amount, currency)
@amount, @currency = StrictDecimal(amount), Currency.find!(currency)
end
|
Instance Attribute Details
#amount ⇒ Object
Returns the value of attribute amount.
16
17
18
|
# File 'lib/cash.rb', line 16
def amount
@amount
end
|
#currency ⇒ Object
Returns the value of attribute currency.
16
17
18
|
# File 'lib/cash.rb', line 16
def currency
@currency
end
|
Instance Method Details
#*(factor) ⇒ Object
74
75
76
77
78
79
|
# File 'lib/cash.rb', line 74
def *(factor)
factor = StrictDecimal(factor)
Cash.new(amount * factor, currency)
rescue ArgumentError
raise ArgumentError, "cannot multiply #{self.inspect} by #{factor}"
end
|
#+(o) ⇒ Object
64
65
66
67
|
# File 'lib/cash.rb', line 64
def +(o)
check_type(o, :add)
Cash.new(amount + o.amount, currency)
end
|
#-(o) ⇒ Object
69
70
71
72
|
# File 'lib/cash.rb', line 69
def -(o)
check_type(o, :subtract)
Cash.new(amount - o.amount, currency)
end
|
#/(factor) ⇒ Object
81
82
83
84
85
86
|
# File 'lib/cash.rb', line 81
def /(factor)
factor = StrictDecimal(factor)
Cash.new(amount / factor, currency)
rescue ArgumentError
raise ArgumentError, "cannot divide #{self.inspect} by #{factor}"
end
|
#<=>(o) ⇒ Object
59
60
61
62
|
# File 'lib/cash.rb', line 59
def <=>(o)
check_type(o, :compare)
amount <=> o.amount
end
|
#amount_string ⇒ Object
55
56
57
|
# File 'lib/cash.rb', line 55
def amount_string
"%.#{currency.offset}f" % amount.round(currency.offset)
end
|
#inspect ⇒ Object
44
45
46
|
# File 'lib/cash.rb', line 44
def inspect
"<Cash #{to_s}>"
end
|
#pretty_print ⇒ Object
36
37
38
|
# File 'lib/cash.rb', line 36
def pretty_print
Format.display(self)
end
|
#StrictDecimal(arg) ⇒ Object
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# File 'lib/cash.rb', line 18
def StrictDecimal(arg)
case arg
when BigDecimal
arg
when Float
fail ArgumentError, "innacurate float for StrictDecimal(): #{arg.inspect}"
when Integer
BigDecimal(arg.to_s)
when String
Float(arg)
BigDecimal(arg)
else
fail TypeError
end
rescue TypeError
fail ArgumentError, "invalid value for StrictDecimal(): #{arg.inspect}"
end
|
#to_h ⇒ Object
48
49
50
51
52
53
|
# File 'lib/cash.rb', line 48
def to_h
{
amount: amount_string,
currency: currency.code
}
end
|
#to_s ⇒ Object
40
41
42
|
# File 'lib/cash.rb', line 40
def to_s
"#{amount_string} #{currency.code}"
end
|