Last active
October 10, 2015 23:38
-
-
Save tomas-stefano/3768618 to your computer and use it in GitHub Desktop.
Simple.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'xmlsimple' | |
module SomeSite | |
class Feed | |
attr_accessor :url, :cache_key, :storage, :xml, :http_adapter | |
# Class responsible to search the uri and save in the store | |
# The store need to implement the #write and #read method. | |
# | |
def initialize(url = 'http://www.somesite.com.br/plantao/rss2.xml', store = Rails.cache, http_adapter = Net::HTTP) | |
@url = url | |
@storage = store | |
@cache_key = 'feed_content' | |
@http_adapter = http_adapter | |
end | |
# Iterates each entry evaluating a block with SomeSite::Feed::Entry as instance. | |
# | |
def each(&block) | |
entries['channel'][0]['item'].each do |entry| | |
block.call(entry) | |
end | |
end | |
# Make a request to the url and return the same object to chain methods. | |
# | |
def get | |
@xml = http_adapter.get(URI.parse(@url)) | |
self | |
end | |
# Find in the storage for the default cache_key | |
# | |
def find | |
@xml = storage.read(@cache_key) | |
end | |
# Make the xml parse and return all nodes from feed content | |
# | |
def entries | |
XmlSimple.xml_in(find) | |
end | |
# Save the xml attribute in the datastore | |
# | |
def save | |
get.storage.write(@cache_key, @xml) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment