Created
July 21, 2009 01:39
-
-
Save rich/151049 to your computer and use it in GitHub Desktop.
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 '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