Class: Money

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Comparable
Defined in:
lib/money/money.rb,
lib/money/errors.rb,
lib/money/helpers.rb,
lib/money/version.rb,
lib/money/currency.rb,
lib/money/allocator.rb,
lib/money/null_currency.rb,
lib/money/currency/loader.rb

Defined Under Namespace

Modules: Helpers Classes: Allocator, Currency, Error, IncompatibleCurrencyError, NullCurrency, ReverseOperationProxy

Constant Summary collapse

NULL_CURRENCY =
NullCurrency.new.freeze
VERSION =
"0.14.7"

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, currency) ⇒ Money

Returns a new instance of Money.

Raises:

  • (ArgumentError)


93
94
95
96
97
98
# File 'lib/money/money.rb', line 93

def initialize(value, currency)
  raise ArgumentError if value.nan?
  @currency = Helpers.value_to_currency(currency)
  @value = value.round(@currency.minor_units)
  freeze
end

Class Attribute Details

.default_currencyObject

Returns the value of attribute default_currency.



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

def default_currency
  @default_currency
end

.parserObject

Returns the value of attribute parser.



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

def parser
  @parser
end

Instance Attribute Details

#currencyObject (readonly)

Returns the value of attribute currency.



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

def currency
  @currency
end

#valueObject (readonly)

Returns the value of attribute value.



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

def value
  @value
end

Class Method Details

.current_currencyObject



64
65
66
# File 'lib/money/money.rb', line 64

def current_currency
  Thread.current[:money_currency]
end

.current_currency=(currency) ⇒ Object



68
69
70
# File 'lib/money/money.rb', line 68

def current_currency=(currency)
  Thread.current[:money_currency] = currency
end

.default_settingsObject



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

def default_settings
  self.parser = MoneyParser
  self.default_currency = Money::NULL_CURRENCY
end

.from_cents(cents, currency = nil) ⇒ Object



38
39
40
# File 'lib/money/money.rb', line 38

def from_cents(cents, currency = nil)
  new(cents.round.to_f / 100, currency)
end

.from_subunits(subunits, currency_iso, format: :iso4217) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/money/money.rb', line 42

def from_subunits(subunits, currency_iso, format: :iso4217)
  currency = Helpers.value_to_currency(currency_iso)

  subunit_to_unit_value = if format == :iso4217
    currency.subunit_to_unit
  elsif format == :stripe
    Helpers::STRIPE_SUBUNIT_OVERRIDE.fetch(currency.iso_code, currency.subunit_to_unit)
  else
    raise ArgumentError, "unknown format #{format}"
  end

  value = Helpers.value_to_decimal(subunits) / subunit_to_unit_value
  new(value, currency)
end

.new(value = 0, currency = nil) ⇒ Object Also known as: from_amount



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/money/money.rb', line 16

def new(value = 0, currency = nil)
  value = Helpers.value_to_decimal(value)
  currency = Helpers.value_to_currency(currency)

  if value.zero?
    @@zero_money ||= {}
    @@zero_money[currency.iso_code] ||= super(Helpers::DECIMAL_ZERO, currency)
  else
    super(value, currency)
  end
end

.parse(*args, **kwargs) ⇒ Object



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

def parse(*args, **kwargs)
  parser.parse(*args, **kwargs)
end

.rational(money1, money2) ⇒ Object



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

def rational(money1, money2)
  money1.send(:arithmetic, money2) do
    factor = money1.currency.subunit_to_unit * money2.currency.subunit_to_unit
    Rational((money1.value * factor).to_i, (money2.value * factor).to_i)
  end
end

.with_currency(new_currency) ⇒ Object

Set Money.default_currency inside the supplied block, resets it to the previous value when done to prevent leaking state. Similar to I18n.with_locale and ActiveSupport’s Time.use_zone. This won’t affect instances being created with explicitly set currency.



76
77
78
79
80
81
82
83
84
# File 'lib/money/money.rb', line 76

def with_currency(new_currency)
  begin
    old_currency = Money.current_currency
    Money.current_currency = new_currency
    yield
  ensure
    Money.current_currency = old_currency
  end
end

.zero(currency = NULL_CURRENCY) ⇒ Object Also known as: empty



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

def zero(currency = NULL_CURRENCY)
  new(0, currency)
end

Instance Method Details

#*(numeric) ⇒ Object



153
154
155
156
157
158
# File 'lib/money/money.rb', line 153

def *(numeric)
  unless numeric.is_a?(Numeric)
    Money.deprecate("Multiplying Money with #{numeric.class.name} is deprecated and will be removed in the next major release.")
  end
  Money.new(value.to_r * numeric, currency)
end

#+(other) ⇒ Object



141
142
143
144
145
# File 'lib/money/money.rb', line 141

def +(other)
  arithmetic(other) do |money|
    Money.new(value + money.value, calculated_currency(money.currency))
  end
end

#-(other) ⇒ Object



147
148
149
150
151
# File 'lib/money/money.rb', line 147

def -(other)
  arithmetic(other) do |money|
    Money.new(value - money.value, calculated_currency(money.currency))
  end
end

#-@Object



130
131
132
# File 'lib/money/money.rb', line 130

def -@
  Money.new(-value, currency)
end

#/(numeric) ⇒ Object



160
161
162
# File 'lib/money/money.rb', line 160

def /(numeric)
  raise "[Money] Dividing money objects can lose pennies. Use #split instead"
end

#<=>(other) ⇒ Object



134
135
136
137
138
139
# File 'lib/money/money.rb', line 134

def <=>(other)
  return unless other.respond_to?(:to_money)
  arithmetic(other) do |money|
    value <=> money.value
  end
end

#==(other) ⇒ Object



168
169
170
# File 'lib/money/money.rb', line 168

def ==(other)
  eql?(other)
end

#absObject



258
259
260
# File 'lib/money/money.rb', line 258

def abs
  Money.new(value.abs, currency)
end

#allocate(splits, strategy = :roundrobin) ⇒ Object



278
279
280
# File 'lib/money/money.rb', line 278

def allocate(splits, strategy = :roundrobin)
  Money::Allocator.new(self).allocate(splits, strategy)
end

#allocate_max_amounts(maximums) ⇒ Object



283
284
285
# File 'lib/money/money.rb', line 283

def allocate_max_amounts(maximums)
  Money::Allocator.new(self).allocate_max_amounts(maximums)
end

#as_json(*args) ⇒ Object



254
255
256
# File 'lib/money/money.rb', line 254

def as_json(*args)
  to_s
end

#calculate_splits(num) ⇒ Hash<Money, Integer>

Calculate the splits evenly without losing pennies. Returns the number of high and low splits and the value of the high and low splits. Where high represents the Money value with the extra penny and low a Money without the extra penny.

Examples:

Money.new(100, "USD").calculate_splits(3) #=> {Money.new(34) => 1, Money.new(33) => 2}

Parameters:

  • number (2)

    of parties.

Returns:

Raises:

  • (ArgumentError)


310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/money/money.rb', line 310

def calculate_splits(num)
  raise ArgumentError, "need at least one party" if num < 1
  subunits = self.subunits
  low = Money.from_subunits(subunits / num, currency)
  high = Money.from_subunits(low.subunits + 1, currency)

  num_high = subunits % num

  {}.tap do |result|
    result[high] = num_high if num_high > 0
    result[low] = num - num_high
  end
end

#centsObject



109
110
111
112
# File 'lib/money/money.rb', line 109

def cents
  # Money.deprecate('`money.cents` is deprecated and will be removed in the next major release. Please use `money.subunits` instead. Keep in mind, subunits are currency aware.')
  (value * 100).to_i
end

#clamp(min, max) ⇒ Object

Clamps the value to be within the specified minimum and maximum. Returns self if the value is within bounds, otherwise a new Money object with the closest min or max value.

Examples:

Money.new(50, "CAD").clamp(1, 100) #=> Money.new(50, "CAD")

Money.new(120, "CAD").clamp(0, 100) #=> Money.new(100, "CAD")

Raises:

  • (ArgumentError)


332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/money/money.rb', line 332

def clamp(min, max)
  raise ArgumentError, 'min cannot be greater than max' if min > max

  clamped_value = min if self.value < min
  clamped_value = max if self.value > max

  if clamped_value.nil?
    self
  else
    Money.new(clamped_value, self.currency)
  end
end

#coerce(other) ⇒ Object

Raises:

  • (TypeError)


203
204
205
206
# File 'lib/money/money.rb', line 203

def coerce(other)
  raise TypeError, "Money can't be coerced into #{other.class}" unless other.is_a?(Numeric)
  [ReverseOperationProxy.new(other), self]
end

#encode_with(coder) ⇒ Object



104
105
106
107
# File 'lib/money/money.rb', line 104

def encode_with(coder)
  coder['value'] = @value.to_s('F')
  coder['currency'] = @currency.iso_code
end

#eql?(other) ⇒ Boolean

TODO: Remove once cross-currency mathematical operations are no longer allowed

Returns:

  • (Boolean)


173
174
175
176
177
# File 'lib/money/money.rb', line 173

def eql?(other)
  return false unless other.is_a?(Money)
  return false unless currency.compatible?(other.currency)
  value == other.value
end

#floorObject



262
263
264
# File 'lib/money/money.rb', line 262

def floor
  Money.new(value.floor, currency)
end

#fraction(rate) ⇒ Object

Raises:

  • (ArgumentError)


270
271
272
273
274
275
# File 'lib/money/money.rb', line 270

def fraction(rate)
  raise ArgumentError, "rate should be positive" if rate < 0

  result = value / (1 + rate)
  Money.new(result, currency)
end

#init_with(coder) ⇒ Object



100
101
102
# File 'lib/money/money.rb', line 100

def init_with(coder)
  initialize(Helpers.value_to_decimal(coder['value']), coder['currency'])
end

#inspectObject



164
165
166
# File 'lib/money/money.rb', line 164

def inspect
  "#<#{self.class} value:#{self} currency:#{self.currency}>"
end

#no_currency?Boolean

Returns:

  • (Boolean)


126
127
128
# File 'lib/money/money.rb', line 126

def no_currency?
  currency.is_a?(NullCurrency)
end

#round(ndigits = 0) ⇒ Object



266
267
268
# File 'lib/money/money.rb', line 266

def round(ndigits=0)
  Money.new(value.round(ndigits), currency)
end

#split(num) ⇒ Array<Money, Money, Money>

Split money amongst parties evenly without losing pennies.

Examples:

Money.new(100, "USD").split(3) #=> [Money.new(34), Money.new(33), Money.new(33)]

Parameters:

  • number (2)

    of parties.

Returns:



295
296
297
# File 'lib/money/money.rb', line 295

def split(num)
  calculate_splits(num).sum([]) { |value, count| Array.new(count, value) }
end

#subunits(format: :iso4217) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
# File 'lib/money/money.rb', line 114

def subunits(format: :iso4217)
  subunit_to_unit_value = if format == :iso4217
    @currency.subunit_to_unit
  elsif format == :stripe
    Helpers::STRIPE_SUBUNIT_OVERRIDE.fetch(@currency.iso_code, @currency.subunit_to_unit)
  else
    raise ArgumentError, "unknown format #{format}"
  end

  (@value * subunit_to_unit_value).to_i
end

#to_dObject



222
223
224
# File 'lib/money/money.rb', line 222

def to_d
  value
end

#to_json(options = {}) ⇒ Object



250
251
252
# File 'lib/money/money.rb', line 250

def to_json(options = {})
  to_s
end

#to_liquidObject



246
247
248
# File 'lib/money/money.rb', line 246

def to_liquid
  cents
end

#to_money(curr = nil) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/money/money.rb', line 208

def to_money(curr = nil)
  if !curr.nil? && no_currency?
    return Money.new(value, curr)
  end

  curr = Helpers.value_to_currency(curr)
  unless currency.compatible?(curr)
    Money.deprecate("mathematical operation not permitted for Money objects with different currencies #{curr} and #{currency}. " \
      "A Money::IncompatibleCurrencyError will raise in the next major release")
  end

  self
end

#to_s(style = nil) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/money/money.rb', line 226

def to_s(style = nil)
  units = case style
  when :legacy_dollars
    2
  when :amount, nil
    currency.minor_units
  else
    raise ArgumentError, "Unexpected style: #{style}"
  end

  rounded_value = value.round(units)
  if units == 0
    sprintf("%d", rounded_value)
  else
    sign = rounded_value < 0 ? '-' : ''
    rounded_value = rounded_value.abs
    sprintf("%s%d.%0#{units}d", sign, rounded_value.truncate, rounded_value.frac * (10 ** units))
  end
end