While working on any e-commerce application,we need to deal with money and currency conversion.Money-Rails gem can be used for that. Money-Rails is a Ruby Library that integrates money gem with Rails.
Some of the advantages of using this gem are given below:
It offers a money class that contains valuable information about certain amount of money, including its currency and value.
It shows monetary values as integers, in cents.Which avoids floating point rounding errors.
Money conversion from one currency to another using APIs
First, we add the gem in gemfile and then run bundle install:
gem 'money-rails'
![](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)
![](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)
For example, we create a Transaction model which has an integer column called price_cents.
class Transaction < ActiveRecord::Base
monetize :price_cents
end
![](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)
![](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)
Here 'monetize' is used to specify the fields, we want to deal with Money objects and helpers provided by the money gem.
Money-rails supports a set of options for monetized fields. The default option is given in the configuration initializer of money-rails:
# config/initializers/money.rb
MoneyRails.configure do |config|
# set the default currency
config.default_currency = :usd
end
![](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)
![](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)
A Money::Currency instance holds all the information about the currency.
currency = Money.new(1000, "USD").currency
currency.iso_code #=> "USD"
currency.name #=> "United States Dollar"
![](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)
![](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)
Money default is USD.This can be overwritten using:
Money.default_currency = Money::Currency.new("CAD")
0 Comment(s)