Class: Money

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Comparable
Defined in:
lib/money/money.rb,
lib/money/config.rb,
lib/money/errors.rb,
lib/money/helpers.rb,
lib/money/railtie.rb,
lib/money/version.rb,
lib/money/currency.rb,
lib/money/allocator.rb,
lib/money/parser/fuzzy.rb,
lib/money/null_currency.rb,
lib/money/parser/simple.rb,
lib/money/currency/loader.rb,
lib/money/parser/accounting.rb,
lib/money/parser/locale_aware.rb,
lib/money/rails/job_argument_serializer.rb

Defined Under Namespace

Modules: Helpers, Parser, Rails Classes: Allocator, Config, Currency, Error, IncompatibleCurrencyError, NullCurrency, Railtie, ReverseOperationProxy

Constant Summary collapse

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

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)


82
83
84
85
86
87
# File 'lib/money/money.rb', line 82

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

Class Attribute Details

.configObject

Returns the value of attribute config.



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

def config
  @config
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

.configure {|config| ... } ⇒ Object

Yields:



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

def configure
  self.config ||= Config.new
  yield(config) if block_given?
end

.current_currencyObject



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

def current_currency
  Thread.current[:money_currency]
end

.current_currency=(currency) ⇒ Object



62
63
64
# File 'lib/money/money.rb', line 62

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

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



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

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



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/money/money.rb', line 23

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

.rational(money1, money2) ⇒ Object



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

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.



70
71
72
73
74
75
76
77
78
# File 'lib/money/money.rb', line 70

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

Instance Method Details

#*(numeric) ⇒ Object

Raises:

  • (ArgumentError)


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

def *(numeric)
  raise ArgumentError, "Money objects can only be multiplied by a Numeric" unless numeric.is_a?(Numeric)

  return self if numeric == 1
  Money.new(value.to_r * numeric, currency)
end

#+(other) ⇒ Object



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

def +(other)
  arithmetic(other) do |money|
    return self if money.value.zero? && !no_currency?
    Money.new(value + money.value, calculated_currency(money.currency))
  end
end

#-(other) ⇒ Object



132
133
134
135
136
137
# File 'lib/money/money.rb', line 132

def -(other)
  arithmetic(other) do |money|
    return self if money.value.zero? && !no_currency?
    Money.new(value - money.value, calculated_currency(money.currency))
  end
end

#-@Object



114
115
116
# File 'lib/money/money.rb', line 114

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

#/(numeric) ⇒ Object



146
147
148
# File 'lib/money/money.rb', line 146

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

#<=>(other) ⇒ Object



118
119
120
121
122
123
# File 'lib/money/money.rb', line 118

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

#==(other) ⇒ Object



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

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

#absObject



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

def abs
  abs = value.abs
  return self if value == abs
  Money.new(abs, currency)
end

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



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

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

#allocate_max_amounts(maximums) ⇒ Object



288
289
290
# File 'lib/money/money.rb', line 288

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

#as_json(options = nil) ⇒ Object



249
250
251
252
253
254
255
# File 'lib/money/money.rb', line 249

def as_json(options = nil)
  if (options.is_a?(Hash) && options.delete(:legacy_format)) || Money.config.legacy_json_format
    to_s
  else
    { value: to_s(:amount), currency: currency.to_s }
  end
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)


315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/money/money.rb', line 315

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

#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)


337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/money/money.rb', line 337

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)


189
190
191
192
# File 'lib/money/money.rb', line 189

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



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

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)


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

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

#floorObject



263
264
265
266
267
# File 'lib/money/money.rb', line 263

def floor
  floor = value.floor
  return self if floor == value
  Money.new(floor, currency)
end

#fraction(rate) ⇒ Object

Raises:

  • (ArgumentError)


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

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



89
90
91
# File 'lib/money/money.rb', line 89

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

#inspectObject



150
151
152
# File 'lib/money/money.rb', line 150

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

#no_currency?Boolean

Returns:

  • (Boolean)


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

def no_currency?
  currency.is_a?(NullCurrency)
end

#round(ndigits = 0) ⇒ Object



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

def round(ndigits=0)
  round = value.round(ndigits)
  return self if round == value
  Money.new(round, 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:



300
301
302
# File 'lib/money/money.rb', line 300

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

#subunits(format: :iso4217) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
# File 'lib/money/money.rb', line 98

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



212
213
214
# File 'lib/money/money.rb', line 212

def to_d
  value
end

#to_fs(style = nil) ⇒ Object Also known as: to_s, to_formatted_s



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/money/money.rb', line 216

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

  rounded_value = value.round(units)
  if units == 0
    sprintf("%d", rounded_value)
  else
    formatted = rounded_value.to_s("F")
    decimal_digits = formatted.size - formatted.index(".") - 1
    (units - decimal_digits).times do
      formatted << '0'
    end
    formatted
  end
end

#to_json(options = nil) ⇒ Object



241
242
243
244
245
246
247
# File 'lib/money/money.rb', line 241

def to_json(options = nil)
  if (options.is_a?(Hash) && options.delete(:legacy_format)) || Money.config.legacy_json_format
    to_s
  else
    as_json(options).to_json
  end
end

#to_money(curr = nil) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/money/money.rb', line 194

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)
    msg = "mathematical operation not permitted for Money objects with different currencies #{curr} and #{currency}"
    if Money.config.legacy_deprecations
      Money.deprecate("#{msg}. A Money::IncompatibleCurrencyError will raise in the next major release")
    else
      raise Money::IncompatibleCurrencyError, msg
    end
  end

  self
end