Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- require 'rubygems'
- require 'nokogiri'
- class String
- def highlight(target)
- return self if (!self[/\b#{target}\b/])
- # To avoid stomping on strings embedded inside links we'll use Nokogiri to
- # parse the string into a DocumentFragment, then we'll look inside the text
- # of the fragment and highlight what we find there.
- html = Nokogiri::HTML::fragment(self.dup)
- html.traverse do |_node|
- (_node.text? && _node.text[ /\b#{ target }\b/ ]) or next
- puts "text node content: #{ _node.content }"
- replacement = _node.content.dup.gsub( /\b#{ target }\b/, "<b>#{ target }</b>" )
- puts "should see: #{ replacement }"
- _node.swap(replacement)
- # For double the fun, do it again for a bus error! WHEEEEEeeeeee!
- # _node.swap(replacement)
- end
- html.to_html
- end
- end
- text = "To avoid stomping on strings embedded inside links we'll use Nokogiri to"
- puts "I'm getting: #{ text.highlight('stomping') }"
Add Comment
Please, Sign In to add comment