eu_central_bank Gem

repository·main·Indexed 42 days ago

https://github.com/rubymoney/eu_central_bank

A Ruby gem that provides a way to download and use exchange rates from the European Central Bank (ECB). Designed for compatibility with the money gem, it allows developers to perform currency conversions using real-world ECB data, including support for historical rates, local XML caching, and rate exporting in JSON, Ruby, and YAML formats.

Tokens
2.6K
Snippets
14
Records
15
Agent score
53%

What's inside eu_central_bank

  1. Cache exchange rates to a file

    main

    To improve performance and avoid frequent network requests, you can save and load rates from a local XML file. The gem adds an updated_at field to the cached data, allowing you to check when the rates were last refreshed.

    • save_rates(path): Saves the current rates to the specified file path.
    • update_rates(path): Reads the rates from the specified file path instead of downloading from the ECB.
    • rates_updated_at: Returns the timestamp of the last update from the cache.
    cache = "/some/file/location/exchange_rates.xml"
    
    # Save rates to a file
    eu_bank.save_rates(cache)
    
    # Read rates from a file
    eu_bank.update_rates(cache)
    
    # Example: Conditional update if cache is older than 1 day
    if !eu_bank.rates_updated_at || eu_bank.rates_updated_at < Time.now - 1.days
      eu_bank.save_rates(cache)
      eu_bank.update_rates(cache)
    end
  2. Configure eu_central_bank as the default Money bank

    main

    To use the European Central Bank rates with the money gem, instantiate EuCentralBank and assign it to Money.default_bank. This allows you to use standard Money object methods for currency conversion.

    require 'eu_central_bank'
    eu_bank = EuCentralBank.new
    Money.default_bank = eu_bank
  3. Exchange currencies using eu_central_bank

    main

    You can perform conversions using the bank instance directly or via Money objects. The gem provides exchange, exchange_to, and exchange_with methods.

    • exchange(amount, from_currency, to_currency): Returns a new Money object.
    • exchange_to(to_currency): Called on a Money object to convert it to a target currency.
    • exchange_with(money_object, to_currency): Converts a Money object to the target currency.
    # Using the bank instance directly
    eu_bank.exchange(100, "CAD", "USD")
    
    # Using Money objects
    Money.us_dollar(100).exchange_to("CAD")
    
    # Using the exchange_with method
    eu_bank.exchange_with(Money.new(100, "CAD"), "USD")
  4. Update exchange rates from the ECB

    main

    Before performing any exchange rate calculations, you must call update_rates to download the latest rates from the European Central Bank. If you do not call this, the bank may not have the necessary data for conversion.

    eu_bank.update_rates
  5. Perform currency exchanges with EuCentralBank

    main

    The EuCentralBank class provides two primary methods for conversion:

    1. exchange(cents, from_currency, to_currency, date=nil): Converts an integer amount of cents from one currency to another.
    2. exchange_with(from, to_currency, date=nil): Takes a Money object as the from argument and converts it to the target currency.

    Both methods support an optional date parameter. If the direct rate between from and to is not found in the store, the bank will attempt to calculate it using EUR as a base (e.g., (to_base_rate / from_base_rate)).

    bank = EuCentralBank.new
    
    # Using cents and ISO codes
    # Converts 10000 cents (100.00) from USD to GBP
    result = bank.exchange(10000, 'USD', 'GBP')
    
    # Using a Money object
    from_money = Money.new(10000, 'USD')
    result = bank.exchange_with(from_money, 'GBP', Date.today)
    
    # Using the legacy options hash for date
    result = bank.exchange(10000, 'USD', 'GBP', { date: Date.today })
  6. Use the EuCentralBank class to manage exchange rates

    main

    The EuCentralBank class is a subclass of Money::Bank::VariableExchange used to fetch, store, and apply exchange rates from the European Central Bank (ECB). It integrates with the money gem to provide currency conversion capabilities. You can initialize it with a custom rates store, typically Money::RatesStore::StoreWithHistoricalDataSupport.

    require 'eu_central_bank'
    
    # Initialize with a rates store
    store = Money::RatesStore::StoreWithHistoricalDataSupport.new
    bank = EuCentralBank.new(store)
    
    # Update rates from ECB
    bank.update_rates
    
    # Perform an exchange
    # (Assuming rates are loaded)
    result = bank.exchange(10000, 'USD', 'EUR') # 100.00 USD to EUR
  7. Export and Import exchange rates

    main

    You can persist the entire rates store by exporting it to a file or string, and later importing it. Supported formats are :json, :ruby (Marshal), and :yaml.

    • export_rates(format, file = nil, opts = {}): Returns the serialized rates as a string. If a file path is provided, it writes the data to that file.
    • import_rates(format, s, opts = {}): Loads rates from a serialized string s in the specified format and adds them to the store.
    bank = EuCentralBank.new
    
    # Export to a YAML file
    bank.export_rates(:yaml, 'rates.yml')
    
    # Import from a JSON string
    json_data = '{"EUR_USD_AT_2023-01-01": 1.07}'
    bank.import_rates(:json, json_data)
  8. Iterate over all stored rates with each_rate

    main

    You can iterate through all exchange rates stored in the StoreWithHistoricalDataSupport instance using the each_rate method. This method yields a tuple containing the source currency, destination currency, the rate, and the date (if applicable).

    store.each_rate do |iso_from, iso_to, rate, date|
      puts "From: #{iso_from}, To: #{iso_to}, Rate: #{rate}, Date: #{date || 'Current'}"
    end
  9. Update exchange rates from the ECB

    main

    Use update_rates to fetch the latest daily exchange rates from the ECB. You can optionally provide a cache (a path to a local file) or a specific url to use as the source.

    To fetch historical data, use update_historical_rates. By default, this fetches the last 90 days of data, but you can pass all: true to fetch the full historical dataset.

    bank = EuCentralBank.new
    
    # Update current daily rates
    bank.update_rates
    
    # Update last 90 days of historical rates
    bank.update_historical_rates
    
    # Update all available historical rates
    bank.update_historical_rates(all: true)
  10. Add and retrieve exchange rates with historical data using StoreWithHistoricalDataSupport

    main

    The Money::RatesStore::StoreWithHistoricalDataSupport class allows you to store and retrieve exchange rates for specific dates. This is useful when you need to manage historical exchange rate data rather than just the current spot rate.

    Use add_rate to insert a rate and get_rate to retrieve it. Both methods accept an optional date parameter (as a Date object or nil for current rates).

    # Adding a rate for a specific date
    store.add_rate('USD', 'EUR', 0.92, Date.new(2023, 1, 1))
    
    # Retrieving a rate for a specific date
    rate = store.get_rate('USD', 'EUR', Date.new(2023, 1, 1))
    
    # Retrieving the current (non-historical) rate
    current_rate = store.get_rate('USD', 'EUR')
  11. Save and load exchange rates to a local cache

    main

    To avoid frequent network requests to the ECB, you can save the raw XML rates to a local file and use that file as a cache.

    • save_rates(cache, url): Downloads the XML from url and writes it to cache.
    • save_historical_rates(cache, all: false): Downloads either the 90-day or all-time historical XML and saves it to cache.
    • update_rates(cache): When called with a cache argument, it parses the local file instead of fetching from the internet.
    bank = EuCentralBank.new
    cache_path = 'path/to/ecb_cache.xml'
    
    # Download and save to file
    bank.save_rates(cache_path)
    
    # Use the local file for updates (offline/cached mode)
    bank.update_rates(cache_path)