Skip to content

Instantly share code, notes, and snippets.

@rich
Created July 21, 2009 01:39
Show Gist options
  • Save rich/151049 to your computer and use it in GitHub Desktop.
Save rich/151049 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'nokogiri'
require 'activesupport'
class NokoHash
def self.from_s(str)
self.new(Nokogiri::XML(str))
end
def initialize(doc)
@doc = doc.class.name =~ /::Document$/ ? doc.root : doc
end
def [](key)
els = case key
when Fixnum
@doc.at(key)
else
@doc.xpath(key.to_s, key.to_s.camelize)
end
value_or_hash(els)
end
def method_missing(meth, *args, &block)
return value_or_hash(@doc.send(meth, *args, &block)) if @doc.respond_to?(meth)
self[meth.to_s.camelize]
end
def value_or_hash(els)
return els.first.content if els.respond_to?(:size) && els.size == 1 && els.first.children.size == 1
return nil if els.respond_to?(:size) && els.size == 1 && els.first.children.size == 0
return els.present? ? NokoHash.new(els) : nil if els.class.name =~ /^Nokogiri::/
els
end
def each(&block)
@doc.each {|el| block.call(NokoHash.new(el))}
end
def map(&block)
@doc.map {|el| block.call(NokoHash.new(el))}
end
alias :collect :map
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment