Skip to content

Instantly share code, notes, and snippets.

@mrk21
Created August 21, 2014 05:39
Show Gist options
  • Save mrk21/29bee9c727b2d27e1dcf to your computer and use it in GitHub Desktop.
Save mrk21/29bee9c727b2d27e1dcf to your computer and use it in GitHub Desktop.
XMLをObjectに変換
require 'faraday'
require 'rexml/document'
require 'ostruct'
require 'uri'
require 'pp'
def get(name)
conn = Faraday::Connection.new(url: 'https://services.addons.mozilla.org')
response = conn.get(URI.encode "/ja/firefox/api/1.5/search/#{name}")
doc = REXML::Document.new(response.body)
build = lambda do |elem|
obj = OpenStruct.new
elem.attributes.each do |(k,v)|
obj.send("#{k}=", v)
end
celems = elem.elements
if celems.empty? then
obj.to_s = elem.texts.join.strip
else
celems.each do |elem|
value = obj.send(elem.name)
if value.nil? then
obj.send("#{elem.name}=", build[elem])
else
obj.send("#{elem.name}=", [value]) unless value.instance_of? Array
obj.send(elem.name).push build[elem]
end
end
end
return obj
end
build[doc.root]
end
pp get('Vimperator').addon.first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment