Guest User

Untitled

a guest
Feb 21st, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. require 'rubygems'
  2. require 'nokogiri'
  3.  
  4. class Nokogiri::XML::Node
  5. def method_missing name, *args, &block
  6. if args.empty?
  7. list = xpath("//#{name}")
  8. elsif args.first.is_a? Hash
  9. hash = args.first
  10. if hash[:css]
  11. list = css("#{name}#{hash[:css]}")
  12. elsif hash[:xpath]
  13. conds = Array(hash[:xpath]).collect{|j| "[#{j}]"}
  14. list = xpath("//#{name}#{conds}")
  15. end
  16. else
  17. list = css("#{name}#{args.first}")
  18. end
  19. list.length == 1 ? list.first : list
  20. end
  21. end
  22.  
  23. HTML = <<-eohtml
  24. <html>
  25. <body>
  26. <ul>
  27. <li class='red'>one</li>
  28. <li class='blue'>two</li>
  29. </ul>
  30. </body>
  31. </html>
  32. eohtml
  33.  
  34. describe "sweetness" do
  35. attr_reader :doc
  36.  
  37. before(:each) do
  38. @doc = Nokogiri(HTML.dup)
  39. end
  40.  
  41. it "allows chaining of tag names" do
  42. doc.html.body.ul.li.first.text.should == "one"
  43. end
  44.  
  45. it "allows string args for css selectors" do
  46. doc.html.body.ul.li(".blue").text.should == "two"
  47. end
  48.  
  49. it "allows hash args for css selectors" do
  50. doc.html.body.ul.li(:css => ".blue").text.should == "two"
  51. end
  52.  
  53. it "works with xpath stuff that I don't really get" do
  54. doc.html.body.ul.li(:xpath => "position()=2").text.should == "two"
  55. doc.html.body.ul.li(:xpath => ["contains(text(),'o')"]).first.text.should == "one"
  56. doc.html.body.ul.li(:xpath => ["contains(text(),'o')","contains(text(),'t')"]).text.should == "two"
  57. end
  58. end
Add Comment
Please, Sign In to add comment