A Ruby Library for Dealing with Money and Currency Conversion.

RubyMoney - Money    

⚠️ 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.
  • This app requires JSON. If you're using JRuby < 1.7.0 you'll need to add gem "json" to your Gemfile or similar.

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'

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

Author: RubyMoney
Source code: https://github.com/RubyMoney/money
License: MIT license

#ruby  #ruby-on-rails 

What is GEEK

Buddha Community

A Ruby Library for Dealing with Money and Currency Conversion.

A Ruby Library for Dealing with Money and Currency Conversion.

RubyMoney - Money    

⚠️ 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.
  • This app requires JSON. If you're using JRuby < 1.7.0 you'll need to add gem "json" to your Gemfile or similar.

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'

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

Author: RubyMoney
Source code: https://github.com/RubyMoney/money
License: MIT license

#ruby  #ruby-on-rails 

Ruby on Rails Development Services | Ruby on Rails Development

Ruby on Rails is a development tool that offers Web & Mobile App Developers a structure for all the codes they write resulting in time-saving with all the common repetitive tasks during the development stage.

Want to build a Website or Mobile App with Ruby on Rails Framework

Connect with WebClues Infotech, the top Web & Mobile App development company that has served more than 600 clients worldwide. After serving them with our services WebClues Infotech is ready to serve you in fulfilling your Web & Mobile App Development Requirements.

Want to know more about development on the Ruby on Rails framework?

Visit: https://www.webcluesinfotech.com/ruby-on-rails-development/

Share your requirements https://www.webcluesinfotech.com/contact-us/

View Portfolio https://www.webcluesinfotech.com/portfolio/

#ruby on rails development services #ruby on rails development #ruby on rails web development company #ruby on rails development company #hire ruby on rails developer #hire ruby on rails developers

Shardul Bhatt

Shardul Bhatt

1626850869

7 Reasons to Trust Ruby on Rails

Ruby on Rails is an amazing web development framework. Known for its adaptability, it powers 3,903,258 sites internationally. Ruby on Rails development speeds up the interaction within web applications. It is productive to such an extent that a Ruby on Rails developer can develop an application 25% to 40% quicker when contrasted with different frameworks. 

Around 2.1% (21,034) of the best 1 million sites utilize Ruby on Rails. The framework is perfect for creating web applications in every industry. Regardless of whether it's medical services or vehicles, Rails carries a higher degree of dynamism to each application. 

Be that as it may, what makes the framework so mainstream? Some say that it is affordable, some say it is on the grounds that the Ruby on Rails improvement environment is simple and basic. There are numerous reasons that make it ideal for creating dynamic applications.

Read more: Best Ruby on Rails projects Examples

7 reasons Ruby on Rails is preferred

There are a few other well-known backend services for web applications like Django, Flask, Laravel, and that's only the tip of the iceberg. So for what reason should organizations pick Ruby on Rails application development? We believe the accompanying reasons will feature why different organizations trust the framework -

Quick prototyping 

Rails works on building MVPs in a couple of months. Organizations incline toward Ruby on Rails quick application development as it offers them more opportunity to showcase the elements. Regular development groups accomplish 25% to 40% higher efficiency when working with Rails. Joined with agile, Ruby on Rails empowers timely delivery.

Basic and simple 

Ruby on Rails is easy to arrange and work with. It is not difficult to learn also. Both of these things are conceivable as a result of Ruby. The programming language has one of the most straightforward sentence structures, which is like the English language. Ruby is a universally useful programming language, working on things for web applications. 

Cost-effective 

Probably the greatest advantage of Rails is that it is very reasonable. The system is open-source, which implies there is no licensing charge included. Aside from that, engineers are additionally effectively accessible, that too at a lower cost. There are a large number of Ruby on Rails engineers for hire at an average compensation of $107,381 each year. 

Startup-friendly

Ruby on Rails is regularly known as "the startup technology." It offers adaptable, fast, and dynamic web improvement to new companies. Most arising organizations and new businesses lean toward this as a direct result of its quick application improvement capacities. It prompts quicker MVP development, which permits new companies to rapidly search for venture investment. 

Adaptable framework 

Ruby on Rails is profoundly adaptable and versatile. In any event, when engineers miss adding any functions, they can utilize different modules to add highlights into the application. Aside from that, they can likewise reclassify components by eliminating or adding them during the development environment. Indeed, even individual projects can be extended and changed. 

Convention over configuration

Regardless of whether it's Ruby on Rails enterprise application development or ecommerce-centered applications, the system utilizes convention over configuration. Developers don't have to go through hours attempting to set up the Ruby on Rails improvement environment. The standard conventions cover everything, improving on things for engineers on the task. The framework likewise utilizes the standard of "Don't Repeat Yourself" to guarantee there are no redundancies. 

Versatile applications 

At the point when organizations scale, applications regularly slack. However, this isn't the situation with Ruby on Rails web application development. The system powers sites with high traffic, It can deal with a huge load of worker demands immediately. Adaptability empowers new businesses to keep utilizing the structure even after they prepare their first model for dispatch. 

Checkout Pros and Cons of Ruby on Rails for Web Development

Bottom Line 

Ruby on Rails is as yet a significant framework utilized by organizations all over the world - of every kind. In this day and age, it is probably the best framework to digitize endeavors through powerful web applications.

A software development company provides comprehensive Ruby on Rails development to guarantee startups and MNCs can benefit as much as possible from their digital application needs. 

Reach us today for a FREE CONSULTATION

#ruby on rails development #ruby on rails application development #ruby on rails web application development #ruby on rails developer

Bella Garvin

Bella Garvin

1625302026

Daily Deals App Development Company I Daily Deals Website Development

Orbit Edge is a daily deals app development company that has 10+ years of experience in daily deals app development services. Our robust, informative, and easy-to-use daily deals app delivers a best-in-class user experience.

#daily deals app development #daily deals app development services #daily deals website development #best daily deals apps #hire daily deals app developers

How does tinder make money?

Essential information regarding how do dating apps make money and how does tinder make money. Moreover, we present unique ways to make money through dating apps.

#how does tinder make money #how does bumble make money #how much money do dating apps make #how dating apps make money #how do dating apps make money