I used Nokogiri and a piece of ActiveSupport to parse an xml file from a given URL, format the data properly and return a JSON string. The script works as expected, so I'm only wondering if there are ways to make the code better from architecture/naming perspectives.
#!/usr/bin/env ruby
$:.unshift File.dirname(__FILE__)
require 'open-uri'
require 'nokogiri'
require 'active_support/core_ext'
class Scadenzario
def initialize(url)
@url = url
@events = parse_events
end
def xml
Nokogiri::XML::Document.parse(open(@url))
end
def to_json
@events.to_json
end
private
def parse_events
result = []
xml.xpath('//item').each do |node|
result << build_event(node)
end
result
end
def build_event(node)
event = Hash.new
event[:title] = node.at_xpath('title').content
event[:url] = node.at_xpath('link').content
event[:start] = format_event_time(node)
event[:allDay] = false
event
end
def format_event_time(node)
Time.parse(node.at_xpath('pubDate').content).iso8601
end
end
puts Scadenzario.new('servizi.seac.it/documenti/rss/rss_scadenzario_annuale.xml').to_json
The parse_events
method can be written like this, but I think it would make the code rather unclear.
def parse_events
xml.xpath('//item').inject([]) do |result, node|
result << build_event(node)
end
end