Guest User

Untitled

a guest
Jul 16th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. require 'rubygems'
  4. require 'nokogiri'
  5.  
  6. class String
  7. def highlight(target)
  8.  
  9. return self if (!self[/\b#{target}\b/])
  10.  
  11. # To avoid stomping on strings embedded inside links we'll use Nokogiri to
  12. # parse the string into a DocumentFragment, then we'll look inside the text
  13. # of the fragment and highlight what we find there.
  14.  
  15. html = Nokogiri::HTML::fragment(self.dup)
  16. html.traverse do |_node|
  17. (_node.text? && _node.text[ /\b#{ target }\b/ ]) or next
  18.  
  19. puts "text node content: #{ _node.content }"
  20.  
  21. replacement = _node.content.dup.gsub( /\b#{ target }\b/, "<b>#{ target }</b>" )
  22. puts "should see: #{ replacement }"
  23.  
  24. _node.swap(replacement)
  25. # For double the fun, do it again for a bus error! WHEEEEEeeeeee!
  26. # _node.swap(replacement)
  27. end
  28. html.to_html
  29. end
  30. end
  31.  
  32. text = "To avoid stomping on strings embedded inside links we'll use Nokogiri to"
  33. puts "I'm getting: #{ text.highlight('stomping') }"
Add Comment
Please, Sign In to add comment