lib/fixer/feed.rb in fixer-0.4 vs lib/fixer/feed.rb in fixer-0.5.0
- old
+ new
@@ -1,27 +1,48 @@
+require 'net/http'
require 'nokogiri'
-require 'open-uri'
module Fixer
- class Feed
- def initialize(type)
- @type = type
- end
+ class Feed
+ include Enumerable
- def get
- doc = Nokogiri::XML(feed)
- doc.xpath('/gesmes:Envelope/xmlns:Cube/xmlns:Cube', doc.root.namespaces).map do |node|
- Builder.new(node).build
- end
- end
+ FEEDS = {
+ current: 'daily',
+ ninety_days: 'hist-90d',
+ historical: 'hist'
+ }
- private
+ def initialize(feed = :current)
+ @feed = FEEDS[feed] or raise ArgumentError
+ end
- def feed
- open(path).read
- end
+ def each(&block)
+ xml
+ .xpath('/gesmes:Envelope/xmlns:Cube/xmlns:Cube', namespaces)
+ .each do |day|
+ day.xpath('./xmlns:Cube').each do |fx|
+ yield date: day['time'],
+ iso_code: fx['currency'],
+ rate: Float(fx['rate'])
+ end
+ end
+ end
- def path
- "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-#{@type}.xml"
- end
- end
+ private
+
+ def body
+ Net::HTTP.get uri
+ end
+
+ def namespaces
+ xml.root.namespaces
+ end
+
+ def uri
+ URI "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-#{@feed}.xml"
+ end
+
+ def xml
+ Nokogiri::XML body
+ end
+ end
end