Last active
August 29, 2015 14:03
-
-
Save tomasc/970d9e59b3b1c45c11b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'nokogiri' | |
module Modulor | |
# Performs gsub while ignoring HTML tags and their attributes. | |
# | |
# Usage: | |
# repl = Modulor::StringReplacer.new('<a href="/en/Foo" class="foo">foo</a>') | |
# repl.gsub(/foo/i, 'bar') | |
# repl.to_html => '<a href="/en/Foo" class='foo'>bar</a>' | |
class StringReplacer | |
def initialize html_fragment | |
@html_fragment = html_fragment.to_s | |
@doc = Nokogiri::HTML::DocumentFragment.parse(@html_fragment) | |
end | |
# --------------------------------------------------------------------- | |
def to_s | |
@doc.to_s | |
end | |
def to_html | |
@doc.to_html | |
end | |
# --------------------------------------------------------------------- | |
def gsub from, to | |
return unless from.present? | |
@doc.xpath('.//*').each do |node| | |
node.inner_html = node.inner_html.gsub(from, to) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment