Git Product home page Git Product logo

money's Introduction

RubyMoney - Money

Gem Version Ruby Code Climate Inline docs License

⚠️ Please read the migration notes before upgrading to a new major version.

If you miss String parsing, check out the new monetize gem.

Contributing

See the Contribution Guidelines

Introduction

A Ruby Library for dealing with money and currency conversion.

Features

  • Provides a Money class which encapsulates all information about a certain amount of money, such as its value and its currency.
  • Provides a Money::Currency class which encapsulates all information about a monetary unit.
  • Represents monetary values as integers, in cents. This avoids floating point rounding errors.
  • Represents currency as Money::Currency instances providing a high level of flexibility.
  • Provides APIs for exchanging money from one currency to another.

Resources

Notes

  • Your app must use UTF-8 to function with this library. There are a number of non-ASCII currency attributes.

Downloading

Install stable releases with the following command:

gem install money

The development version (hosted on Github) can be installed with:

git clone git://github.com/RubyMoney/money.git
cd money
rake install

Usage

require 'money'

# explicitly define locales
I18n.config.available_locales = :en
Money.locale_backend = :i18n

# 10.00 USD
money = Money.from_cents(1000, "USD")
money.cents     #=> 1000
money.currency  #=> Currency.new("USD")

# Comparisons
Money.from_cents(1000, "USD") == Money.from_cents(1000, "USD")   #=> true
Money.from_cents(1000, "USD") == Money.from_cents(100, "USD")    #=> false
Money.from_cents(1000, "USD") == Money.from_cents(1000, "EUR")   #=> false
Money.from_cents(1000, "USD") != Money.from_cents(1000, "EUR")   #=> true

# Arithmetic
Money.from_cents(1000, "USD") + Money.from_cents(500, "USD") == Money.from_cents(1500, "USD")
Money.from_cents(1000, "USD") - Money.from_cents(200, "USD") == Money.from_cents(800, "USD")
Money.from_cents(1000, "USD") / 5                            == Money.from_cents(200, "USD")
Money.from_cents(1000, "USD") * 5                            == Money.from_cents(5000, "USD")

# Unit to subunit conversions
Money.from_amount(5, "USD") == Money.from_cents(500, "USD")  # 5 USD
Money.from_amount(5, "JPY") == Money.from_cents(5, "JPY")    # 5 JPY
Money.from_amount(5, "TND") == Money.from_cents(5000, "TND") # 5 TND

# Currency conversions
some_code_to_setup_exchange_rates
Money.from_cents(1000, "USD").exchange_to("EUR") == Money.from_cents(some_value, "EUR")

# Swap currency
Money.from_cents(1000, "USD").with_currency("EUR") == Money.from_cents(1000, "EUR")

# Formatting (see Formatting section for more options)
Money.from_cents(100, "USD").format #=> "$1.00"
Money.from_cents(100, "GBP").format #=> "£1.00"
Money.from_cents(100, "EUR").format #=> "€1.00"

Currency

Currencies are consistently represented as instances of Money::Currency. The most part of Money APIs allows you to supply either a String or a Money::Currency.

Money.from_cents(1000, "USD") == Money.from_cents(1000, Money::Currency.new("USD"))
Money.from_cents(1000, "EUR").currency == Money::Currency.new("EUR")

A Money::Currency instance holds all the information about the currency, including the currency symbol, name and much more.

currency = Money.from_cents(1000, "USD").currency
currency.iso_code #=> "USD"
currency.name     #=> "United States Dollar"

To define a new Money::Currency use Money::Currency.register as shown below.

curr = {
  priority:            1,
  iso_code:            "USD",
  iso_numeric:         "840",
  name:                "United States Dollar",
  symbol:              "$",
  subunit:             "Cent",
  subunit_to_unit:     100,
  decimal_mark:        ".",
  thousands_separator: ","
}

Money::Currency.register(curr)

The pre-defined set of attributes includes:

  • :priority a numerical value you can use to sort/group the currency list
  • :iso_code the international 3-letter code as defined by the ISO 4217 standard
  • :iso_numeric the international 3-digit code as defined by the ISO 4217 standard
  • :name the currency name
  • :symbol the currency symbol (UTF-8 encoded)
  • :subunit the name of the fractional monetary unit
  • :subunit_to_unit the proportion between the unit and the subunit
  • :decimal_mark character between the whole and fraction amounts
  • :thousands_separator character between each thousands place

All attributes except :iso_code are optional. Some attributes, such as :symbol, are used by the Money class to print out a representation of the object. Other attributes, such as :name or :priority, exist to provide a basic API you can take advantage of to build your application.

:priority

The priority attribute is an arbitrary numerical value you can assign to the Money::Currency and use in sorting/grouping operation.

For instance, let's assume your Rails application needs to render a currency selector like the one available here. You can create a couple of custom methods to return the list of major currencies and all currencies as follows:

# Returns an array of currency id where
# priority < 10
def major_currencies(hash)
  hash.inject([]) do |array, (id, attributes)|
    priority = attributes[:priority]
    if priority && priority < 10
      array[priority] ||= []
      array[priority] << id
    end
    array
  end.compact.flatten
end

# Returns an array of all currency id
def all_currencies(hash)
  hash.keys
end

major_currencies(Money::Currency.table)
# => [:usd, :eur, :gbp, :aud, :cad, :jpy]

all_currencies(Money::Currency.table)
# => [:aed, :afn, :all, ...]

Default Currency

By default Money defaults to USD as its currency. This can be overwritten using:

Money.default_currency = Money::Currency.new("CAD")

If you use Rails, then config/initializers/money.rb is a very good place to put this.

Currency Exponent

The exponent of a money value is the number of digits after the decimal separator (which separates the major unit from the minor unit). See e.g. ISO 4217 for more information. You can find the exponent (as an Integer) by

Money::Currency.new("USD").exponent  # => 2
Money::Currency.new("JPY").exponent  # => 0
Money::Currency.new("MGA").exponent  # => 1

Currency Lookup

To find a given currency by ISO 4217 numeric code (three digits) you can do

Money::Currency.find_by_iso_numeric(978) #=> Money::Currency.new(:eur)

Currency Exchange

Exchanging money is performed through an exchange bank object. The default exchange bank object requires one to manually specify the exchange rate. Here's an example of how it works:

Money.add_rate("USD", "CAD", 1.24515)
Money.add_rate("CAD", "USD", 0.803115)

Money.us_dollar(100).exchange_to("CAD")  # => Money.from_cents(124, "CAD")
Money.ca_dollar(100).exchange_to("USD")  # => Money.from_cents(80, "USD")

Comparison and arithmetic operations work as expected:

Money.from_cents(1000, "USD") <=> Money.from_cents(900, "USD")   # => 1; 9.00 USD is smaller
Money.from_cents(1000, "EUR") + Money.from_cents(10, "EUR") == Money.from_cents(1010, "EUR")

Money.add_rate("USD", "EUR", 0.5)
Money.from_cents(1000, "EUR") + Money.from_cents(1000, "USD") == Money.from_cents(1500, "EUR")

Exchange rate stores

The default bank is initialized with an in-memory store for exchange rates.

Money.default_bank = Money::Bank::VariableExchange.new(Money::RatesStore::Memory.new)

You can pass your own store implementation, i.e. for storing and retrieving rates off a database, file, cache, etc.

Money.default_bank = Money::Bank::VariableExchange.new(MyCustomStore.new)

Stores must implement the following interface:

# Add new exchange rate.
# @param [String] iso_from Currency ISO code. ex. 'USD'
# @param [String] iso_to Currency ISO code. ex. 'CAD'
# @param [Numeric] rate Exchange rate. ex. 0.0016
#
# @return [Numeric] rate.
def add_rate(iso_from, iso_to, rate); end

# Get rate. Must be idempotent. i.e. adding the same rate must not produce duplicates.
# @param [String] iso_from Currency ISO code. ex. 'USD'
# @param [String] iso_to Currency ISO code. ex. 'CAD'
#
# @return [Numeric] rate.
def get_rate(iso_from, iso_to); end

# Iterate over rate tuples (iso_from, iso_to, rate)
#
# @yieldparam iso_from [String] Currency ISO string.
# @yieldparam iso_to [String] Currency ISO string.
# @yieldparam rate [Numeric] Exchange rate.
#
# @return [Enumerator]
#
# @example
#   store.each_rate do |iso_from, iso_to, rate|
#     puts [iso_from, iso_to, rate].join
#   end
def each_rate(&block); end

# Wrap store operations in a thread-safe transaction
# (or IO or Database transaction, depending on your implementation)
#
# @yield [n] Block that will be wrapped in transaction.
#
# @example
#   store.transaction do
#     store.add_rate('USD', 'CAD', 0.9)
#     store.add_rate('USD', 'CLP', 0.0016)
#   end
def transaction(&block); end

# Serialize store and its content to make Marshal.dump work.
#
# Returns an array with store class and any arguments needed to initialize the store in the current state.

# @return [Array] [class, arg1, arg2]
def marshal_dump; end

The following example implements an ActiveRecord store to save exchange rates to a database.

# rails g model exchange_rate from:string to:string rate:float

class ExchangeRate < ApplicationRecord
  def self.get_rate(from_iso_code, to_iso_code)
    rate = find_by(from: from_iso_code, to: to_iso_code)
    rate&.rate
  end

  def self.add_rate(from_iso_code, to_iso_code, rate)
    exrate = find_or_initialize_by(from: from_iso_code, to: to_iso_code)
    exrate.rate = rate
    exrate.save!
  end

  def self.each_rate
    return find_each unless block_given?

    find_each do |rate|
      yield rate.from, rate.to, rate.rate
    end
  end

  def self.marshal_dump
    [self]
  end
end

The following example implements a Redis store to save exchange rates to a redis database.

class RedisRateStore
  INDEX_KEY_SEPARATOR = '_TO_'.freeze

  # Using second db of the redis instance
  # because sidekiq uses the first db
  REDIS_DATABASE = 1

  # Using Hash to store rates data
  REDIS_STORE_KEY = 'rates'

  def initialize
    conn_url = "#{Rails.application.credentials.redis_server}/#{REDIS_DATABASE}"
    @connection = Redis.new(url: conn_url)
  end

  def add_rate(iso_from, iso_to, rate)
    @connection.hset(REDIS_STORE_KEY, rate_key_for(iso_from, iso_to), rate)
  end

  def get_rate(iso_from, iso_to)
    @connection.hget(REDIS_STORE_KEY, rate_key_for(iso_from, iso_to))
  end

  def each_rate
    rates = @connection.hgetall(REDIS_STORE_KEY)
    return to_enum(:each_rate) unless block_given?

    rates.each do |key, rate|
      iso_from, iso_to = key.split(INDEX_KEY_SEPARATOR)
      yield iso_from, iso_to, rate
    end
  end

  def transaction
    yield
  end

  private

  def rate_key_for(iso_from, iso_to)
    [iso_from, iso_to].join(INDEX_KEY_SEPARATOR).upcase
  end
end

Now you can use it with the default bank.

# For Rails 6 pass model name as a string to make it compatible with zeitwerk
# Money.default_bank = Money::Bank::VariableExchange.new("ExchangeRate")
Money.default_bank = Money::Bank::VariableExchange.new(ExchangeRate)

# Add to the underlying store
Money.default_bank.add_rate('USD', 'CAD', 0.9)
# Retrieve from the underlying store
Money.default_bank.get_rate('USD', 'CAD') # => 0.9
# Exchanging amounts just works.
Money.from_cents(1000, 'USD').exchange_to('CAD') #=> #<Money fractional:900 currency:CAD>

There is nothing stopping you from creating store objects which scrapes XE for the current rates or just returns rand(2):

Money.default_bank = Money::Bank::VariableExchange.new(StoreWhichScrapesXeDotCom.new)

You can also implement your own Bank to calculate exchanges differently. Different banks can share Stores.

Money.default_bank = MyCustomBank.new(Money::RatesStore::Memory.new)

If you wish to disable automatic currency conversion to prevent arithmetic when currencies don't match:

Money.disallow_currency_conversion!

Implementations

The following is a list of Money.gem compatible currency exchange rate implementations.

Formatting

There are several formatting rules for when Money#format is called. For more information, check out the formatting module source, or read the latest release's rdoc version.

If you wish to format money according to the EU's Rules for expressing monetary units in either English, Irish, Latvian or Maltese:

m = Money.from_cents('123', :gbp) # => #<Money fractional:123 currency:GBP>
m.format(symbol: m.currency.to_s + ' ') # => "GBP 1.23"

Rounding

By default, Money objects are rounded to the nearest cent and the additional precision is not preserved:

Money.from_amount(2.34567).format #=> "$2.35"

To retain the additional precision, you will also need to set infinite_precision to true.

Money.default_infinite_precision = true
Money.from_amount(2.34567).format #=> "$2.34567"

To round to the nearest cent (or anything more precise), you can use the round method. However, note that the round method on a Money object does not work the same way as a normal Ruby Float object. Money's round method accepts different arguments. The first argument to the round method is the rounding mode, while the second argument is the level of precision relative to the cent.

# Float
2.34567.round     #=> 2
2.34567.round(2)  #=> 2.35

# Money
Money.default_infinite_precision = true
Money.from_cents(2.34567).format       #=> "$0.0234567"
Money.from_cents(2.34567).round.format #=> "$0.02"
Money.from_cents(2.34567).round(BigDecimal::ROUND_HALF_UP, 2).format #=> "$0.0235"

You can set the default rounding mode by passing one of the BigDecimal mode enumerables like so:

Money.rounding_mode = BigDecimal::ROUND_HALF_EVEN

See BigDecimal::ROUND_MODE for more information

Ruby on Rails

To integrate money in a Rails application use money-rails.

For deprecated methods of integrating with Rails, check the wiki.

Localization

In order to localize formatting you can use I18n gem:

Money.locale_backend = :i18n

With this enabled a thousands seperator and a decimal mark will get looked up in your I18n translation files. In a Rails application this may look like:

# config/locale/en.yml
en:
  number:
    currency:
      format:
        delimiter: ","
        separator: "."
  # falling back to
  number:
    format:
      delimiter: ","
      separator: "."

For this example Money.from_cents(123456789, "SEK").format will return 1,234,567.89 kr which otherwise would have returned 1 234 567,89 kr.

This will work seamlessly with rails-i18n gem that already has a lot of locales defined.

If you wish to disable this feature and use defaults instead:

Money.locale_backend = nil

Deprecation

The current default behaviour always checks the I18n locale first, falling back to "per currency" localization. This is now deprecated and will be removed in favour of explicitly defined behaviour in the next major release.

If you would like to use I18n localization (formatting depends on the locale):

Money.locale_backend = :i18n

# example (using default localization from rails-i18n):
I18n.locale = :en
Money.from_cents(10_000_00, 'USD').format # => $10,000.00
Money.from_cents(10_000_00, 'EUR').format # => €10,000.00

I18n.locale = :es
Money.from_cents(10_000_00, 'USD').format # => $10.000,00
Money.from_cents(10_000_00, 'EUR').format # => €10.000,00

If you need to localize the position of the currency symbol, you have to pass it manually. Note: this will become the default formatting behavior in the next version.

I18n.locale = :fr
format = I18n.t :format, scope: 'number.currency.format'
Money.from_cents(10_00, 'EUR').format(format: format) # => 10,00 €

For the legacy behaviour of "per currency" localization (formatting depends only on currency):

Money.locale_backend = :currency

# example:
Money.from_cents(10_000_00, 'USD').format # => $10,000.00
Money.from_cents(10_000_00, 'EUR').format # => €10.000,00

In case you don't need localization and would like to use default values (can be redefined using Money.default_formatting_rules):

Money.locale_backend = nil

# example:
Money.from_cents(10_000_00, 'USD').format # => $10000.00
Money.from_cents(10_000_00, 'EUR').format # => €10000.00

Collection

In case you're working with collections of Money instances, have a look at money-collection for improved performance and accuracy.

Troubleshooting

If you don't have some locale and don't want to get a runtime error such as:

I18n::InvalidLocale: :en is not a valid locale

Set the following:

I18n.enforce_available_locales = false

Heuristics

Prior to v6.9.0 heuristic analysis of string input was part of this gem. Since then it was extracted in to money-heuristics gem.

Migration Notes

Version 6.0.0

  • The Money#dollars and Money#amount methods now return instances of BigDecimal rather than Float. We should avoid representing monetary values with floating point types so to avoid a whole class of errors relating to lack of precision. There are two migration options for this change:
    • The first is to test your application and where applicable update the application to accept a BigDecimal return value. This is the recommended path.
    • The second is to migrate from the #amount and #dollars methods to use the #to_f method instead. This option should only be used where Float is the desired type and nothing else will do for your application's requirements.

money's People

Contributors

alovak avatar alup avatar antstorm avatar cade avatar createdbypete avatar ct-clearhaus avatar dalenw avatar enebo avatar epidemian avatar fklingler avatar foobarwidget avatar george-carlin avatar ggilder avatar hadees avatar haletom avatar ismasan avatar j15e avatar jlecour avatar lunks avatar ohthatjames avatar orien avatar phlegx avatar printercu avatar semmons99 avatar seongreen avatar spk avatar tagliala avatar tsyber1an avatar viettienn avatar weppos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

money's Issues

Formatting not working in the model

I have the following code in my Model (after the necessary compsed_of calls):

after_validation :update_changelog

  def update_changelog
    if self.changed?
      change = "Price: Low = #{self.price_low.format(:with_currency => true)}, High = #{self.price_high.format(:with_currency => true)} | Retail Value: Low = #{self.retail_low.format(:with_currency => true)}, High = #{self.retail_high.format(:with_currency => true)} | Set: #{Time.now.to_s(:long)} | #{self.currency}"
      if !self.changelog.blank?
        self.changelog = self.changelog + "\r\n" + change
      else
        self.changelog = change
      end
    end
  end

No matter what I do, it is using the default currency of 'USD' despite the fact that this price is in 'EUR'. In my log, the currency param is showing 'eur'. Is it impossible to access the currency from the model or am I just doing it wrong?

Thanks in advance

String#to_money doesn't respect subunit_to_unit

describe "String#to_money" do
  it "should respect :subunit_to_unit currency property" do
    "1".to_money("USD").should == Money.new(1_00,  "USD")
    "1".to_money("TND").should == Money.new(1_000, "TND")
    "1".to_money("CLP").should == Money.new(1,     "CLP")
  end
end

Wrong documentation about creating new currency

Documentation states:

  Money::Currency::TABLE[:usd] = {
   :priority => 1,
   :iso_code => "USD",
   :name     => "United States Dollar",
   :symbol   => "$",
   :subunit  => "Cent"
   :subunit_to_unit => "100",
   :separator => ".",
   :delimiter =? ","
}

But, if we do so, at least Money#to_s and Money#format fail with error:

String can't be coerced into Float

If we declare :subunit_to_unit as integer everything works.

Subunit Name in HKD should be cent / cents instead of "Ho"

In Hong Kong, "Ho" is commonly used in daily life, but

1 Dollars = 10 "Ho"s and
1 Dollars = 100 Cents

Banking / accounting need cents resolution.
So "Ho" is not suitable to be used as sub-unit and sub-unit name.

If speaking in English, we call 1 "Ho" as 10 cents, "Ho" is only available in Cantonese.

GemSpec and required_rubygems_version

I'm having many issues trying to install Money on Heroku and Engine Yard.
In both cases, the error is

Installing money (3.1.0) /usr/ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/installer.rb:169:in `install': money requires RubyGems version >= 1.3.7. Try 'gem update --system' to update RubyGems itself. (Gem::InstallError) 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/source.rb:100:in `install' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:55:in `run' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:44:in `run' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:8:in `install' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/cli.rb:217:in `install' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `send' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `run' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor.rb:246:in `dispatch' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/base.rb:389:in `start' 
from /usr/ruby1.8.7/lib/ruby/gems/1.8/gems/bundler-1.0.0/bin/bundle:13 
from /usr/ruby1.8.7/bin/bundle:19:in `load' 
from /usr/ruby1.8.7/bin/bundle:19

I'm wondering if we can lower the minimum RubyGems version at least to 1.3.6 like Rails does.

Currency issue in model(Rails)

Configuration:

Money.default_currency = Money::Currency.new("AED")

Model:

composed_of
:balance,
:class_name => "Money",
:mapping => [ %w(balance_cents cents), %w(currency currency_as_string) ],
:constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
:converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }

In console:
Company.new(:balance => 100, :currency => "EUR")

gives

Company id: nil, :balance_cents: 10000, currency: "AED"

Which is WRONG. currency should be "EUR".

[PATCH] Set Money::SYMBOLS, Money::SEPARATORS and Money::DELIMITERS deprecation target to 3.2

I deprecated Money::SYMBOLS, Money::SEPARATORS and Money::DELIMITERS when I created Money::Currency in #4.

One major release passed after it (Money 3), I think we can consider to bump set the deprecation target to Money 3.2 (as set for the Bank class).

I'm attaching a patch for this. I'm also refactoring the small Deprecation "framework" so that we can use it elsewhere in Money. For instance, I need it in #14.

[RFE] ISO 4217 currency number

It would be really nice to have the ISO 4217 currency number, as well as the three letter code.
That way people don't need to have a separate lookup table, to match the currency number, to the three letter code.

Our (And I believe most) payment gateway, uses the number, instead of the three letter code.

Use BigDecimal instead of Float

I'm running into issues when testing against 1.9.2 where Float is losing it's precision. What do you think about changing any usage of Float to BigDecimal when doing calculations?

Money is not i18n ready

It's not true, but it works :)

monkey patching

require 'money'

class Money
  include ActionView::Helpers::NumberHelper

  def to_s
    number_with_delimiter(
      sprintf("%.2f", cents / 100.00),
      I18n.translate(:'number.format.separator'),
      I18n.translate(:'number.format.delimiter')
     )
  end
end

[PATCH] Represent currencies as Currency object

In my money fork I added the ability to represent currencies with Money::Currency.
http://github.com/weppos/money

Additional changes:

  • definition for almost all existing currencies
  • changed the documentation to reflect the Currency feature
  • added Money#symbol, Money#delimiter and Money#separator convenient methods
  • added deprecation warning whenever applicable

All commits are submitted along with a corresponding test suite.

I hope you would merge my changes to the mainstream repository.
I worked hard to ensure backward-compatibility with existing API.

-- Simone

Weird error I get very often

When the Money-attribute (say :price) is nil, any of these lines fails:

self.price ||= Money.new(0)
self.price = Money.new(0) if self.price.nil?

with error:

undefined method `round' for nil:NilClass

I had this issue in some other scenarios as well, but don't remember which ones as I solved them with some rescue block then.

Reason?

format issue

In format in money.rb, there's a small issue with the subunit formatting for currencies with subunit_to_unit != 100. Starting on line 859, the code should be something like:

if rules[:no_cents] or currency.subunit_to_unit == 1
  formatted = sprintf("#{symbol_value}%d", self.to_f)
elsif currency.subunit_to_unit == 10 || currency.subunit_to_unit == 5
  formatted = sprintf("#{symbol_value}%.1f", self.to_f)      
elsif currency.subunit_to_unit == 1000
  formatted = sprintf("#{symbol_value}%.3f", self.to_f)      
else
  formatted = sprintf("#{symbol_value}%.2f", self.to_f)
end

For the subunit_to_unit == 5 case, as long as the cents calculation is working, this should just work...maybe...? ;)

Roger & Onsi

New deprecations

I would deprecate the following legacy behaviors, with target Money 3.3.

  1. format(option1, option2, ...) in favor of format(:option1 => ..., :option2 => ...)
  2. Money.new(:currency => "EUR")

Any objection?

Issue with currencies with subunit_to_unit != 100

Check it out:
"1.5".to_money('KWD').cents
should be 1500
but is 1050

Money.new_with_dollars(1.5, 'KWD').cents
should be 1500
is #.to_i = 1500

We can definitely use new_with_dollars in our code, but do you have thoughts on to_money?

Thanks!
Roger

making the id an integer could make it faster.

To use it in a rails app that stores data in a dabase, it could be better if the currency is stored as an integer, not as a string. it could be accomplished by adding a integer id or may be ussing the ISO code:

ISO_code_list.map do |ISO_code|
  c = ""
    code.each_codepoint do |point|
      c << point.to_s
    end
   integer_ISO_code_list << c
 end

then, if this is stored in the database it will be faster :)

Don't know how to build task 'default'

I updated my master branch, then I tried to run the default task (usually the tests) but it failed.

$ rake
(in /Users/weppos/Code/money)
rake aborted!
Don't know how to build task 'default'

(See full trace by running task with --trace)

The solution is as simple as

# Run tests by default
task :default => :spec

Cleanup core extensions

From #25

There's an small exception to my feedback. We can think about adding more .from_type methods with the purpose to simplify the core extensions provided in the core_extensions.rb file. In this case, we can create

# for the purpose of this example I separate Numeric
# into smaller classes
Money.from_fixnum(value, ...)
Money.from_float(value, ...)
Money.from_bigdecimal(value, ...)

class Fixnum
  def to_money(...)
    Money.from_fixnum(self, ...)
  end
end

class Float
  def to_money(...)
    Money.from_float(self, ...)
  end
end

class BigDecimal
  def to_money(...)
    Money.from_bigdecimal(self, ...)
  end
end

String deserves a special mention here because a String is a very data-rich money format. In fact, there are two types of string representations:

# with currency
"10 $"
"10 USD"
# without currency
"10"

This is the reason why we can try to provide two methods:

# A type-focused method, as for BigDecimal, Fixnum...
# which accepts only digit representations
# "1.0", "1000" and handle them as cents
Money.from_string

# A concept-focused method which implements a more advanced
# (and slow) detection mechanism
Money.parse(...)

The idea behind this change is to clean up the core_extensions by moving all the logic into the Money class.

Initiating Money object with bigdecimal cause stange behaviour

Hi,
I just update from Money 3.1.5 to 3.5.4 (still with ruby 1.8.7) and a curious bug just append when using Money.new_with_dollar (these part of my code worked great before.
I tracked down the bug and it seems Money.format (or to_s) have a probem when initiated with a bigdecimal
Money.new(1212.45.to_d_100).to_s => "1212.0,.0"
Money.new(1212.45_100).to_s => "1212,45"

Below some of my tests...
Money.from_bigdecimal(100.00.to_d).format => "$100.0,.0"
you see the stange ,. between the zeros
Money.from_bigdecimal(BigDecimal.new(100.00.to_s)).to_s => "100.0,.0"
used as in Monay.from_numeric, same error
Money.new_with_dollars("1212.45".to_f, "ILS").format => "₪1 212.0,.0"
I came to it trying from new_with_dollars
Money.new_with_dollars("1212.45".to_f, "ILS").to_f => 1212.45
Note that the value seems to be correct.
Money.new((1212.45.to_d*100).fix).to_s => "1212.0,.0"
"1212,45 EUR".to_money.format => "€1 212,45"

Should @bank.exchange use Money instance instead of cents?

Talking about the following method.

def exchange_to(other_currency)
  other_currency = Currency.wrap(other_currency)
  Money.new(@bank.exchange(self.cents, currency, other_currency), other_currency)
end

I'm now implementing a custom converter which relies on a third party API. All the public API, from Yahoo! to Google Finance works with the real value, not cents.
In other words, you need to pass as value $9.99, not 999.

For this reason, my bank class needs to take the cents amount, create a new Money instance and call .to_s on it.

I'm wondering if it's not more appropriate to change the Money class to pass self, instead of self.cents and let the bank class decide whether it needs to use the money instance itself, or a single property.

What do you think?

no such file to load -- json

Trying to run the tests, I get the following error.

$ rake spec
(in /Users/weppos/Code/money)
/Users/weppos/Code/money/spec/../lib/money/bank/variable_exchange.rb:2:in `require': no such file to load -- json (LoadError)
    from /Users/weppos/Code/money/spec/../lib/money/bank/variable_exchange.rb:2
    from /Users/weppos/Code/money/spec/../lib/money/money.rb:3:in `require'
    from /Users/weppos/Code/money/spec/../lib/money/money.rb:3
    from /Users/weppos/Code/money/spec/../lib/money.rb:24:in `require'
    from /Users/weppos/Code/money/spec/../lib/money.rb:24
    from /Users/weppos/Code/money/spec/spec_helper.rb:5:in `require'
    from /Users/weppos/Code/money/spec/spec_helper.rb:5
    from ./spec/bank/base_spec.rb:1:in `require'
    from ./spec/bank/base_spec.rb:1
    from /Users/weppos/.rvm/gems/ruby-1.8.7-p249/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:15:in `load'
    from /Users/weppos/.rvm/gems/ruby-1.8.7-p249/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:15:in `load_files'
    from /Users/weppos/.rvm/gems/ruby-1.8.7-p249/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:14:in `each'
    from /Users/weppos/.rvm/gems/ruby-1.8.7-p249/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:14:in `load_files'
    from /Users/weppos/.rvm/gems/ruby-1.8.7-p249/gems/rspec-1.3.0/lib/spec/runner/options.rb:133:in `run_examples'
    from /Users/weppos/.rvm/gems/ruby-1.8.7-p249/gems/rspec-1.3.0/lib/spec/runner/command_line.rb:9:in `run'
    from /Users/weppos/.rvm/gems/ruby-1.8.7-p249/gems/rspec-1.3.0/bin/spec:5
rake aborted!
Command /Users/weppos/.rvm/rubies/ruby-1.8.7-p249/bin/ruby -I"lib"  "/Users/weppos/.rvm/gems/ruby-1.8.7-p249/gems/rspec-1.3.0/bin/spec" "spec/bank/base_spec.rb" "spec/bank/variable_exchange_spec.rb" "spec/core_extensions_spec.rb" "spec/currency_spec.rb" "spec/deprecations_spec.rb" "spec/money_spec.rb"  failed

(See full trace by running task with --trace)

The cause is the following line in the variable_exchange.rb file

require 'json'

There are two issues here:

  1. the JSON gem is not listed as runtime dependency in the .gemspec file
  2. the JSON gem is not automatically loaded in Ruby < 1.9. Ruby 1.8.x is not shipped with RubyGems and you have to manually require "rubygems" before loading and Gem dependency.

This issue makes me think if forcing the user to install JSON to have a function he probably won't use is a good idea. Honestly, I believe that the majority of Money users are more focused on working with Money and Currencies rather than exchanging rates.

My proposal is to make JSON import/export optional. We could add a new documentation page to reference the import/export feature so that users are aware of it.
Then, I would change the library to try to require json/yaml, rescue any LoadError and show JSON/YAML export option only if the library is successfully loaded.

In this way, we won't need to force the user to install json library, nor we would need to force loading rubygems unless the user wants to do so.

What do you think?

JPY format

Gentlemen,

>> money = Money.new(100)
=> #<Money cents:100 currency:USD>
>> money.exchange_to("JPY")
=> #<Money cents:8286 currency:JPY>
>> money.exchange_to("JPY").format
=> "¥82.86"

Here, I expect to read ¥83, as the so-called sen is out of circulation since the early 50s and the common practice is to omit the subunits when printing in yen.

Two fixes I can think of is to do away with the subunit in Currency::TABLE (you'll probably not want this) or add more logic to Currency::TABLE and Money#format, like a display_subunit boolean attribute. What say you?

PS: I'm sure there are other currencies with the same formatting issue.

#to_money should accept currency as second optional argument

Something like this:

describe "Money core extensions" do
  specify "#to_money accept currency" do
    %w{EUR USD}.each do |curr|
      money = 1234.to_money(curr)
      money.cents.should == 1234_00
      money.currency.should == Money::Currency.new(curr)
      money.should == Money.new(1234_00, curr)

      money = "10.10".to_money(curr)
      money.cents.should = 10_10
      money.currency.should == Money::Currency.new(curr)
      money.should == Money.new(10_10, curr)

      '10 JPY'.to_money(curr).should == Money.new(10_00, curr) # or raise?
    end
  end
end

$5.99 with no cents equal 5$ !?

Working on the gem since few weeks, refactoring some parts and writing tests and so on...

I was implementing a :precision argument for the format method when I saw this :

Money.ca_dollar(599).format(:no_cents => true).should == "$5"

  • What !!!!! 5 equal 6 ?! no way.
    Is it a normal behaviour or may I correct this ?!

numeric to_money has rounding error

This test snippet fails...

amount = 555.55.to_money
assert_equal(Money.new(55555), amount)

Probably the error is in to ruby internal to_int method. "555.55".to_money works fine.

Here's the error message I get:
<#<Money:0x7f119cad3590
@bank=
#<Money::VariableExchangeBank:0x7f119e581a68
@mutex=#Mutex:0x7f119e5819f0,
@rates={},
@rounding_method=nil>,
@cents=55555,
@Currency=
#<Money::Currency id: usd priority: 1, iso_code: USD, name: United States Dollar, symbol: $, subunit: Cent, subunit_to_unit: 100, separator: ., delimiter: ,>>> expected but was
<#<Money:0x7f119cad35b8
@bank=
#<Money::VariableExchangeBank:0x7f119e581a68
@mutex=#Mutex:0x7f119e5819f0,
@rates={},
@rounding_method=nil>,
@cents=55554,
@Currency=
#<Money::Currency id: usd priority: 1, iso_code: USD, name: United States Dollar, symbol: $, subunit: Cent, subunit_to_unit: 100, separator: ., delimiter: ,>>>.

#describe vs #context, #specify vs #it

Looking at the RSpec files, I saw many different test styles. The two prominent styles are

  1. specify "#method should ..."
  2. describe "#method" { it ... }

Examples

specify "Money.empty creates a new Money object of 0 cents" do
  Money.empty.should == Money.new(0)
end

vs

describe ".empty" do
  it "creates a new Money object of 0 cents" do
    Money.empty.should == Money.new(0)
  end
end

or

specify "#zero? returns whether the amount is 0" do
  Money.new(0, "USD").should be_zero
  Money.new(0, "EUR").should be_zero
  Money.new(1, "USD").should_not be_zero
  Money.new(10, "YEN").should_not be_zero
  Money.new(-1, "EUR").should_not be_zero
end

vs

describe "#add_rate" do
  it "should add rates correctly" do
    @bank.add_rate("USD", "EUR", 0.788332676)
    @bank.add_rate("EUR", "YEN", 122.631477)

    @bank.instance_variable_get(:@rates)['USD_TO_EUR'].should == 0.788332676
    @bank.instance_variable_get(:@rates)['EUR_TO_JPY'].should == 122.631477
  end

  it "should treat currency names case-insensitively" do
    @bank.add_rate("usd", "eur", 1)
    @bank.instance_variable_get(:@rates)['USD_TO_EUR'].should == 1
  end
end

I would suggest to adopt an unique style. So far, the most arising habit I have seen is to use one describe for every method and one or more it for every test.

describe '#exchange' do
  it 'should raise NotImplementedError' do
    lambda { @bank.exchange(100, 'USD', 'EUR') }.should raise_exception(NotImplementedError)
  end
end

describe '#exchange_with' do
  it 'should raise NotImplementedError' do
    lambda { @bank.exchange_with(Money.new(100, 'USD'), 'EUR') }.should raise_exception(NotImplementedError)
  end
end

describe '#same_currency?' do
  it 'should accept str/str' do
    lambda{@bank.send(:same_currency?, 'USD', 'EUR')}.should_not raise_exception
  end

  it 'should accept currency/str' do
    lambda{@bank.send(:same_currency?, Money::Currency.wrap('USD'), 'EUR')}.should_not raise_exception
  end
end

Do you agree with this style?

Negative value accepted in constructor

(Bumping from comment in a closed issue)

Does it makes sense to create a Money object with negative values?

I'm currently using the money gem for handling a simple expense system and while getting acquainted with the gem I realize I can create a Money object with negative value, such as Money.new(-1000). As a result, if I add this object to another Money it will be used as negative value.

What I'm trying to understand is if this behavior is good thing, because I think it can cause some semantic problems (for instance filtering using input before creating my Money object).

I'd like to hear your comments about this. Thank you very much and nice job on this gem, really helpful!

to_money errors with "25."

using money (2.1.3)

irb(main):001:0> require "rubygems"
=> true
irb(main):002:0> require "money"
=> true
irb(main):003:0> '25.'.to_money
NoMethodError: undefined method `length' for nil:NilClass
    from /usr/local/lib/ruby/gems/1.8/gems/money-2.1.3/lib/money/core_extensions.rb:88:in `calculate_cents'
    from /usr/local/lib/ruby/gems/1.8/gems/money-2.1.3/lib/money/core_extensions.rb:25:in `to_money'
    from (irb):3

"ea." throws off money parsing

The value '$129.99 ea.' parses to 12,999.00

I'm guessing support for extraneous strings like "ea." is out of scope, but I'd also assume it's preferable for an error to be thrown than to return an incorrect value.

Money.parse('$129.99 ea.')
=> #<Money:0x103003738 @Currency=#<Money::Currency id: usd priority: 1, iso_code: USD, name: United States Dollar, symbol: $, subunit: Cent, subunit_to_unit: 100, separator: ., delimiter: ,>, @cents=1299900, @bank=#<Money::Bank::VariableExchange:0x10341a9c0 @mutex=#Mutex:0x10341a920, @rounding_method=nil, @rates={}>>

Ghanaian Cedi

Hi

Currency.rb incorrectly references the Ghanaian cedi as ISO code GHC when it has been GHS since 2007 - see http://en.wikipedia.org/wiki/Ghanaian_cedi. Please could this be corrected?

It would be easier to patch this kind of thing locally if the currency list was implemented as a class variable with an accessor rather than as a constant, as changing a constant generates warnings. Obviously the local source can be patched directly, but it is nicer to be able to avoid doing this. Just a suggestion.

* vs /

Is there any reason why the method / accepts either a Money or Fixnum while * doesn't (or viceversa)?

subunit divisor hard-coded in to_f and format methods

Hi. I'm working with a currency that doesn't have cents (there's just one unit, like the old Italian Lira), so in order to have Money#to_f and Money#format return the correct value, the calculation should be:

Money#cents / currency.subunit_to_unit (so subunit_to_unit == 1 for that currency)

And yet to_f and format are dividing by 100.0 at the moment.

Do you have plans for fixing this? Otherwise I might fork and fix for my own use.

Also: do you have plans for consolidating delimiters and separators as part of the CURRENCIES hash? At the moment they're in different constants, but it would be nice to be able to fully configure a currency in one place.

using money in rails form

i am trying to compose a form to create a new money object. i want to use the composed_of virtual attribute for the amount, and have a drop down for currency. so far the only way i have gotten it to work is to ONLY have an input for the composed_of attribute (price)...OR.... have inputs for cents & currency. but having a user enter an amount in cents is confusing.

if i have both price & currency, the default currency is saved.

what is the preferred way of incorporating a user defined currency into the composed_of price when used in a form?

Money::Currency changed attributes.

Hi there,
I saw that in last commits, the attributes of Money::Currency::Table changed to other names (:decimal_mark, :thousands_separator).
I'm currently building a solution to have customizable currencies lisst, since it is really tough to have a consistente list useful for everyone.
Generaly speeking it is not a good idea to change attributes name, especially without deprecation warnings.
I will integrate these new names, except if they will change any soon ?!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.