# Hpricot Text GSub 0.1.5 # # See the tests at the bottom for usage examples # # Released into the public domain # # Please send bug reports and improvements to # christoffer.sawicki@gmail.com # # Canonical source # http://code.vemod.net/svn/misc/hpricot_goodies/hpricot_text_gsub.rb # # Thanks to Tim Fletcher for telling me how to make the code simpler. require "hpricot" module HpricotTextGSub module NodeWithChildrenExtension def text_gsub!(*args, &block) children.each { |x| x.text_gsub!(*args, &block) } end end module TextNodeExtension def text_gsub!(*args, &block) content.gsub!(*args, &block) end end end Hpricot::Doc.send(:include, HpricotTextGSub::NodeWithChildrenExtension) Hpricot::Elem.send(:include, HpricotTextGSub::NodeWithChildrenExtension) Hpricot::Text.send(:include, HpricotTextGSub::TextNodeExtension) if __FILE__ == $0 require "test/unit" class HpricotTextGSubTest < Test::Unit::TestCase def assert_hpricot_gsub(expected, input, *args, &block) doc = Hpricot(input) doc.text_gsub!(*args, &block) assert_equal(expected, doc.to_s) end def test_with_root input = 'xxx' expected = 'yyy' assert_hpricot_gsub(expected, input, 'xxx', 'yyy') end def test_without_root input = 'xxxxxx' expected = 'yyyyyy' assert_hpricot_gsub(expected, input, 'xxx', 'yyy') end def test_replacement_insertion input = 'xxx' expected = '*xxx*' assert_hpricot_gsub(expected, input, /(xxx)/, '*\1*') end def test_block input = 'xxx' expected = 'xxxzzz' assert_hpricot_gsub(expected, input, 'xxx') { |x| x + "zzz" } end # This would optimally work, but it doesn't because of scoping def test_failure_of_normal_block_insertion_1 input = 'xxx' Hpricot(input).text_gsub!(/(xxx)/) { assert_nil($1) } end # Regexp.last_match doesn't work either :( def test_failure_of_normal_block_insertion_2 input = 'xxx' Hpricot(input).text_gsub!(/(xxx)/) { assert_nil(Regexp.last_match) } end end end