Sha256: 7a8cfc006c791deb94bdfc9caeffae25517c65c27c3cc37942d0baf7ff8df5f4

Contents?: true

Size: 995 Bytes

Versions: 1

Compression:

Stored size: 995 Bytes

Contents

# frozen_string_literal: true

require 'net/http'
require 'rexml/document'

module Fixer
  # Wraps ECB's data feed
  class Feed
    include Enumerable

    SCOPES = {
      current: 'daily',
      ninety_days: 'hist-90d',
      historical: 'hist'
    }.freeze

    def initialize(scope = :current)
      @scope = SCOPES.fetch(scope) { raise ArgumentError }
    end

    def each
      REXML::XPath.each(document, '/gesmes:Envelope/Cube/Cube[@time]') do |day|
        date = Date.parse(day.attribute('time').value)
        REXML::XPath.each(day, './Cube') do |currency|
          yield(
            date: date,
            iso_code: currency.attribute('currency').value,
            rate: Float(currency.attribute('rate').value)
          )
        end
      end
    end

    private

    def document
      REXML::Document.new(xml)
    end

    def xml
      Net::HTTP.get(url)
    end

    def url
      URI("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-#{@scope}.xml")
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fixer-1.0.0 lib/fixer/feed.rb