A lightweight Ruby client for the Fixer.io API, with a natural syntax for currency conversion, decimal arithmetic and comparisons.
require 'fixer_api_client'
using FixerApiClient::NumericExtensions
(100.usd + 50.eur + 2000.cop).to_cop.round(2)- Currency-specific methods such as
100.usd,100.eurand100.cop, enabled through Ruby refinements rather than global monkey patches. - Dynamic conversion methods such as
to_usd,to_eurandto_cop. - Monetary arithmetic using
BigDecimal. - Automatic conversion of currency operands to the left-hand currency when adding or subtracting.
- Numeric operations such as rounding and comparisons.
- Lazy, thread-safe, in-memory exchange-rate caching with stale-data fallback.
- No runtime filesystem writes, Rails dependency or external cache service.
Requires Ruby 3.0 or newer.
Add the gem to your application's Gemfile:
gem 'fixer_api_client'Then run:
bundle installAlternatively:
gem install fixer_api_clientTo try the current development checkout in another project before publishing a release, use a local Bundler dependency:
gem 'fixer_api_client', path: '../fixer_api_client'Obtain an API key from Fixer.io and set it in your environment:
export FIXER_IO_API_KEY='your-api-key'| Environment variable | Description |
|---|---|
FIXER_IO_API_KEY |
Required when fetching live exchange rates. |
FIXER_IO_API_URL |
Optional API base URL. Defaults to https://data.fixer.io/api. |
fixer_api_client_tests |
Set to true to use bundled offline test data instead of live rates. Intended for development and testing only. |
Keep API keys out of source control. Use your deployment platform's secret management or environment configuration in production.
The client expects EUR-based rates from Fixer's /latest endpoint. Cross-currency conversions are calculated using EUR as the intermediate currency; no custom base currency is required.
require 'fixer_api_client'
using FixerApiClient::NumericExtensions
amount = 100.usd
amount.value # => BigDecimal representing 100
amount.symbol # => 'usd'
amount.friendly_name # => 'United States Dollar'
amount.to_s # => '100.0 United States Dollar'The refinement is lexical: enable it in the file or scope where you want to use currency-specific numeric methods. Requiring the gem does not globally modify Numeric.
You can also instantiate a currency without enabling the refinement:
FixerApiClient::Currency.new(BigDecimal('100.25'), 'usd', 'United States Dollar')100.usd.to_cop
100.cop.to_eur
100.eur.to_usd
100.usd.convert_to('COP')
100.usd.to_cop.round(2)Conversion results depend on the cached exchange-rate snapshot. Converting to the same currency returns the original object without fetching rates.
Arithmetic returns a new currency object when the result represents money; it does not change the original amount.
100.usd + 50 # => 150.0 United States Dollar
100.usd - 20 # => 80.0 United States Dollar
100.usd * 2 # => 200.0 United States Dollar
100.usd / 4 # => 25.0 United States Dollar
100.usd / 50.usd # => BigDecimal representing 2When adding or subtracting two currencies, the right-hand operand is converted to the currency of the left-hand operand. The same rule applies to chained additions and subtractions:
(1.usd + 1.cop + 1.ars).symbol # => 'usd'
(1.cop + 1.usd + 1.ars).symbol # => 'cop'
100.eur - 50.usd # => Currency in EUR| Operation | Result |
|---|---|
| Currency + or - numeric | Currency in the receiver's denomination |
| Currency + or - currency | Currency in the receiver's denomination |
| Currency * numeric | Currency |
| Currency / numeric | Currency |
| Currency / currency | Dimensionless BigDecimal ratio |
| Currency * currency | TypeError |
| Division by zero | ZeroDivisionError |
Reverse arithmetic (for example, 50 + 100.usd) is not supported by the current implementation; put the currency on the left.
Numeric methods are delegated to the underlying BigDecimal through method_missing. Methods such as abs, round, ceil, floor, truncate and unary plus/minus preserve the currency when they return a number. Other delegated methods return their underlying results.
10.567.usd.round(2) # => 10.57 United States Dollar
(-10).usd.abs # => 10.0 United States Dollar
100.usd.positive? # => true
0.usd.zero? # => true
100.usd.to_i # => 100
100.usd.to_f # => 100.0
100.usd > 50.usd # => true
100.usd == 100.usd # => true
100.usd.between?(50.usd, 150.usd) # => true
100.usd > 50.eur # compares after conversionCurrency includes Ruby's Comparable module. Cross-currency comparisons use the same conversion policy as arithmetic. Unsupported or unavailable rates can raise errors; a symbol in the bundled catalog does not guarantee that Fixer supplies its rate.
Amounts are stored as BigDecimal, and raw API JSON is parsed using decimal_class: BigDecimal, avoiding an intermediate floating-point conversion for decimal rates.
(0.1.usd + 0.2.usd).value == BigDecimal('0.3') # => true
BigDecimal('10.567').usd.round(2)Prefer decimal strings when exact input precision matters. Converting an already imprecise Float to BigDecimal cannot recover lost precision. Division and exchange-rate calculations may still require rounding; the gem does not automatically round conversions to a currency's minor units. Round explicitly when appropriate for your application.
FixerApiClient.available_currencies # array of code/name strings
FixerApiClient.available_conversions # array of conversion method names
FixerApiClient.rates_creation_date # UTC timestamp as a string
FixerApiClient::CurrencyData.symbols # frozen hash of currency codes and names
FixerApiClient::CurrencyData.rates # frozen hash of EUR-based ratesThe rate lookup and creation-date methods may fetch rates if the cache is missing or expired. Decimal rates are BigDecimal; whole-number rates may be Integer.
Currency symbols are shipped as a read-only JSON resource and loaded into memory. Requiring the gem and constructing an amount do not contact Fixer. Rates are fetched only when needed for conversion or explicit rate access.
| Setting | Default |
|---|---|
| Cache lifetime | 24 hours from the API timestamp |
| Maximum stale age | 7 days from the API timestamp |
| Retry delay after failed refresh with usable stale data | 60 seconds |
| Cache scope | One Ruby process |
These settings are constants in the current implementation, not public configuration options.
The client validates HTTP status, API success, EUR base, timestamp freshness and positive finite rates before replacing the cached snapshot. A Mutex serializes cache access and refreshes within a process. Cached data is recursively frozen to protect against accidental mutation. Each individual conversion uses one rate snapshot, but a chain of conversions can span a cache refresh.
If a refresh fails, previously cached rates may be used while they remain within the maximum stale age. If no usable snapshot exists, the client raises FixerApiClient::CurrencyData::FetchError. The retry delay applies only when usable stale data exists.
begin
100.usd.to_cop
rescue FixerApiClient::CurrencyData::FetchError => e
warn e.message
endAn unknown currency or unavailable rate can also raise KeyError. Stale rates may be unsuitable for transactions that require current pricing; inspect the rate timestamp and apply your own freshness policy.
No writable gem directory, installation-time Fixer request, Redis instance or persistent volume is required. The design works with ordinary Ruby processes and deployments on platforms such as Heroku, AWS and Google Cloud, provided outbound HTTPS is available when live rates are needed.
The cache is not shared across processes, workers or containers. Each process starts with an empty live-rate cache and can make its own API requests, including after a restart. This matters when scaling applications or working with a limited API quota. A distributed cache is not currently implemented.
Clone the repository and install dependencies:
git clone https://github.com/jhonhquintero/fixer_api_client.git
cd fixer_api_client
bin/setup
bundle exec rspecYou can also run bundle exec rake spec. The existing RSpec suite stubs HTTP responses and time to exercise cache reuse, refresh, decimal parsing, response validation and failure handling without contacting the live API.
For an interactive session using bundled historical data rather than the API:
fixer_api_client_tests=true bin/consoleusing FixerApiClient::NumericExtensions
100.usd.to_cop.round(2)For live rates, launch bin/console with your API key and without test mode. The development console includes reload! to reload Ruby source files; restarting is safer after changes to constants, refinements or cached state.
Build or install the gem locally from a Git checkout:
bundle exec rake build
bundle exec rake installTo publish a new release, update lib/fixer_api_client/version.rb and the changelog, run the test suite, and then use bundle exec rake release when ready to tag and publish to RubyGems.
- Replace test-specific production branches with VCR/WebMock and isolated test setup.
- Add explicit cache invalidation and configurable cache policies.
- Explore optional shared cache adapters for multi-process deployments.
- Expand arithmetic, conversion and concurrency test coverage.
Bug reports and pull requests are welcome at GitHub.
Available under the MIT License. See LICENSE.txt for details.