Your Rails app stores prices in one currency, and the marketing team wants them shown in the visitor's currency. The quick fix is an HTTP call in a controller. The better fix is three small pieces: a service that fetches and caches rates, a helper that formats money, and a controller concern that picks the currency.
This uses Rails 8 and Ruby 3.3+, with only the standard library for HTTP.
Store the API key in credentials
We use AllRatesToday for live mid-market rates in 160+ currencies. Get a free API key, then:
bin/rails credentials:edit allratestoday: api_key: art_live_xxxxxxxx The service object
The service has one public job: return a hash of rates for a base currency. Everything else (HTTP, caching, failure handling) is private.
# app/services/currency_converter.rb require "net/http" require "json" class CurrencyConverter API_URL = "https://allratestoday.com/api/v1/rates".freeze SUPPORTED = %w[USD EUR GBP JPY CAD AUD CHF INR].freeze TTL = 10.minutes class Error < StandardError; end class RateLimited < Error; end def self.convert(amount, to:, from: "USD") return BigDecimal(amount.to_s) if to == from rate = rates(from).fetch(to) { raise Error, "No rate for #{from}->#{to}" } BigDecimal(amount.to_s) * BigDecimal(rate.to_s) end def self.rates(base = "USD") Rails.cache.fetch(cache_key(base), expires_in: TTL, race_condition_ttl: 30.seconds) do fresh = fetch_rates(base) Rails.cache.write(last_good_key(base), fresh) # no expiry: our safety net fresh end rescue Error, Net::OpenTimeout, Net::ReadTimeout, SocketError => e Rails.logger.warn("[CurrencyConverter] #{e.class}: #{e.message}") Rails.cache.read(last_good_key(base)) || raise end def self.cache_key(base) = "fx/v1/#{base}" def self.last_good_key(base) = "fx/v1/#{base}/last_good" def self.fetch_rates(base) uri = URI(API_URL) targets = SUPPORTED - [base] uri.query = URI.encode_www_form(source: base, target: targets.join(",")) request = Net::HTTP::Get.new(uri) request["Authorization"] = "Bearer #{Rails.application.credentials.dig(:allratestoday, :api_key)}" response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 3, read_timeout: 5) do |http| http.request(request) end case response when Net::HTTPSuccess JSON.parse(response.body).to_h { |row| [row["target"], row["rate"]] } when Net::HTTPUnauthorized raise Error, "Invalid or missing API key" when Net::HTTPTooManyRequests raise RateLimited, "Quota exceeded or rate limited" else raise Error, "HTTP #{response.code}" end end private_class_method :fetch_rates, :cache_key, :last_good_key end What each part does:
- One call per base. The API accepts many targets in one request, and they count as one request. We ask for all supported currencies at once and cache the whole hash.
-
Rails.cache.fetchwithexpires_in. Rates refresh upstream about every 60 seconds. For display prices, 10 minutes is plenty. -
race_condition_ttl. When the entry expires, the first process to notice extends the old value by 30 seconds while it refetches. Other requests keep reading the old value instead of all hitting the API at once. - A last-good copy. If the API returns 401 or 429, or times out, the block raises,
fetchcaches nothing, and we fall back to the most recent successful response. The page keeps working. -
BigDecimal. Multiplying floats gives you49.99 * 0.92 = 45.990800000000004.BigDecimalkeeps the math exact until you round for display.
The response from the API is a JSON array even for one target, which is why we build the hash with to_h over rows.
Check your cache store
In development, Rails uses :null_store unless you turn caching on, so every request hits the API. Run this once:
bin/rails dev:cache In production, Rails 8 defaults to Solid Cache, which works across processes and servers. Redis or Memcached are fine too. The memory store is per process, so avoid it if you run many Puma workers.
The view helper
Formatting is a view concern. Different currencies need different decimals and symbol positions, and number_to_currency needs to be told.
# app/helpers/money_helper.rb module MoneyHelper FORMATS = { "USD" => { unit: "$", precision: 2, format: "%u%n" }, "EUR" => { unit: "€", precision: 2, format: "%n %u", separator: ",", delimiter: "." }, "GBP" => { unit: "£", precision: 2, format: "%u%n" }, "JPY" => { unit: "¥", precision: 0, format: "%u%n" }, "CAD" => { unit: "CA$", precision: 2, format: "%u%n" }, "AUD" => { unit: "A$", precision: 2, format: "%u%n" }, "CHF" => { unit: "CHF", precision: 2, format: "%u %n", delimiter: "’" }, "INR" => { unit: "₹", precision: 2, format: "%u%n" }, }.freeze def localized_price(amount, currency: current_currency, from: "USD") converted = CurrencyConverter.convert(amount, to: currency, from: from) number_to_currency(converted, **FORMATS.fetch(currency)) rescue CurrencyConverter::Error number_to_currency(amount, **FORMATS.fetch(from)) end end number_to_currency rounds half up at the precision you give it, so JPY gets whole yen and the rest get two decimals. If you add the money gem later, this helper is the only place that changes.
The rescue matters. If there are no rates at all (fresh deploy plus API outage), the page shows the base price instead of a 500 error.
Picking the currency per request
A concern keeps the controller code short. It checks a currency param, then a cookie, then falls back to USD.
# app/controllers/concerns/current_currency.rb module CurrentCurrency extend ActiveSupport::Concern included do helper_method :current_currency before_action :remember_currency end private def current_currency @current_currency ||= begin code = (params[:currency] || cookies[:currency]).to_s.upcase CurrencyConverter::SUPPORTED.include?(code) ? code : "USD" end end def remember_currency return unless params[:currency] cookies[:currency] = { value: current_currency, expires: 1.year, same_site: :lax } end end # app/controllers/application_controller.rb class ApplicationController < ActionController::Base include CurrentCurrency end Using it in views
<%# app/views/products/index.html.erb %> <%= form_with url: products_path, method: :get, data: { turbo_action: "replace" } do |f| %> <%= f.select :currency, CurrencyConverter::SUPPORTED, { selected: current_currency }, onchange: "this.form.requestSubmit()" %> <% end %> <% @products.each do |product| %> <article> <h2><%= product.name %></h2> <p class="price"><%= localized_price(product.price) %></p> </article> <% end %> <p class="note">Converted at live mid-market rates. You are charged in USD.</p> With Turbo, the form submit swaps the page without a full reload, and the cookie keeps the choice for later visits.
Testing without network calls
Stub the private fetch in tests. The cache store in the test environment is :null_store by default, so set a memory store for cache-related tests.
# test/services/currency_converter_test.rb require "test_helper" require "minitest/mock" class CurrencyConverterTest < ActiveSupport::TestCase setup { Rails.cache = ActiveSupport::Cache::MemoryStore.new } test "converts with BigDecimal" do CurrencyConverter.stub(:fetch_rates, { "EUR" => 0.92 }) do assert_equal BigDecimal("45.9908"), CurrencyConverter.convert(49.99, to: "EUR") end end test "falls back to last good rates when the API fails" do CurrencyConverter.stub(:fetch_rates, { "EUR" => 0.92 }) { CurrencyConverter.rates } Rails.cache.delete("fx/v1/USD") CurrencyConverter.stub(:fetch_rates, ->(_) { raise CurrencyConverter::RateLimited }) do assert_equal 0.92, CurrencyConverter.rates["EUR"] end end end For how rounding should work when you store converted amounts (not just display them), see the rounding and precision guide.
FAQ
Why a class with class methods and not an instance?
There is no per-call state. If you later need per-tenant API keys, switch to CurrencyConverter.new(api_key:) and keep the same interface.
Should I run a job to refresh rates instead?
You can. A Solid Queue recurring job every 10 minutes that calls CurrencyConverter.rates keeps the cache warm, so no user request ever waits on the API.
Can I store the rate on orders?
Yes, and you should. Save the converted amount, the rate and its timestamp on the order at checkout. Never recompute historical orders from today's rate.
What about invoices that need a government rate?
Some tax rules require an official central-bank rate rather than a market rate. AllRatesToday also serves official central-bank rates; use those for invoices and keep mid-market rates for display.
