Guest User

Untitled

a guest
Feb 21st, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 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. <div>
  31. one
  32. <div>div two</div>
  33. </div>
  34. </body>
  35. </html>
  36. eohtml
  37.  
  38. describe "sweetness" do
  39. attr_reader :doc
  40.  
  41. before(:each) do
  42. @doc = Nokogiri(HTML.dup)
  43. end
  44.  
  45. it "allows chaining of tag names" do
  46. doc.html.body.ul.li.first.text.should == "one"
  47. end
  48.  
  49. it "allows string args for css selectors" do
  50. doc.html.body.ul.li(".blue").text.should == "two"
  51. end
  52.  
  53. it "doesn't go too deep. that is what she said." do
  54. doc.html.body.div.div.text.should == "div two"
  55. end
  56.  
  57. it "allows hash args for css selectors" do
  58. doc.html.body.ul.li(:css => ".blue").text.should == "two"
  59. end
  60.  
  61. it "works with xpath stuff that I don't really get" do
  62. doc.html.body.ul.li(:xpath => "position()=2").text.should == "two"
  63. doc.html.body.ul.li(:xpath => ["contains(text(),'o')"]).first.text.should == "one"
  64. doc.html.body.ul.li(:xpath => ["contains(text(),'o')","contains(text(),'t')"]).text.should == "two"
  65. end
  66. end
Add Comment
Please, Sign In to add comment