How would I construct a Hash from this scenario in Ruby?

113 views Asked by At

Given I have the following code:

  ENDPOINT = 'http://api.eventful.com'
  API_KEY  = 'PbFVZfjTXJQWrnJp'

  def get_xml(url, options={})
    compiled_url = "#{ENDPOINT}/rest#{url}" << "?app_key=#{API_KEY}&sort_order=popularity"
    options.each { |k, v| compiled_url << "&#{k.to_s}=#{v.to_s}" }
    REXML::Document.new((Net::HTTP.get(URI.parse(URI.escape(compiled_url)))))
  end

  def event_search(location, date)
    get_xml('/events/search', 
      :location => "#{location}, United Kingdom",
      :date     => date
    )
  end

And we access the XML data formatted by REXML::Document like this:

events = event_search('London', 'Today').elements

And we can access these elements like this (this prints all the titles in the events):

events.each('search/events/event/title') do |title|
  puts title.text
end

The XML I'm using can be found here. I would like this construct a Hash like so:

{"Title1" => {:title => 'Title1', :date => 'Date1', :post_code => 'PostCode1'}, 
"Title2" => {:title => 'Title2', :date => 'Date2', :post_code => 'PostCode2'}}

When using events.each('search/events/event/title'), events.each('search/events/event/date'), and events.each('search/events/event/post_code').

So I want to create a Hash from the XML provided by the URL I have included above. Thanks!

2

There are 2 answers

0
mckeed On BEST ANSWER

You should loop over the events themselves, not the titles. Something like this

events_by_title = {}
elements.each('search/events/event') do |event|
  title = event.get_elements('title').first.text
  events_by_title[title] = {
    :title => title,
    :date => event.get_elements('start_time').first.text
    :post_code => event.get_elements('postal_code').first.text,
  }
end
1
Bruno Girin On

Get the root element using root() on the REXML:Document object then use each_element("search/events/event") to iterate over "event" node. You can then extract the different values out of it using the different methods on element: http://ruby-doc.org/stdlib-1.9.3/libdoc/rexml/rdoc/REXML/Element.html