-
-
Save tenderlove/29491 to your computer and use it in GitHub Desktop.
This file contains hidden or 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' | |
class Nokogiri::XML::Node | |
def method_missing name, *args, &block | |
if args.empty? | |
list = xpath("./#{name}") | |
elsif args.first.is_a? Hash | |
hash = args.first | |
if hash[:css] | |
list = css("#{name}#{hash[:css]}") | |
elsif hash[:xpath] | |
conds = Array(hash[:xpath]).collect{|j| "[#{j}]"} | |
list = xpath("./#{name}#{conds}") | |
end | |
else | |
list = css("#{name}#{args.first}") | |
end | |
list.length == 1 ? list.first : list | |
end | |
end | |
HTML = <<-eohtml | |
<html> | |
<body> | |
<ul> | |
<li class='red'>one</li> | |
<li class='blue'>two</li> | |
</ul> | |
<div> | |
one | |
<div>div two</div> | |
</div> | |
</body> | |
</html> | |
eohtml | |
describe "sweetness" do | |
attr_reader :doc | |
before(:each) do | |
@doc = Nokogiri(HTML.dup) | |
end | |
it "allows chaining of tag names" do | |
doc.html.body.ul.li.first.text.should == "one" | |
end | |
it "allows string args for css selectors" do | |
doc.html.body.ul.li(".blue").text.should == "two" | |
end | |
it "doesn't go too deep. that is what she said." do | |
doc.html.body.div.div.text.should == "div two" | |
end | |
it "allows hash args for css selectors" do | |
doc.html.body.ul.li(:css => ".blue").text.should == "two" | |
end | |
it "works with xpath stuff that I don't really get" do | |
doc.html.body.ul.li(:xpath => "position()=2").text.should == "two" | |
doc.html.body.ul.li(:xpath => ["contains(text(),'o')"]).first.text.should == "one" | |
doc.html.body.ul.li(:xpath => ["contains(text(),'o')","contains(text(),'t')"]).text.should == "two" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment