Skip to content

Instantly share code, notes, and snippets.

@tomasc
Last active August 29, 2015 14:03
Show Gist options
  • Save tomasc/970d9e59b3b1c45c11b8 to your computer and use it in GitHub Desktop.
Save tomasc/970d9e59b3b1c45c11b8 to your computer and use it in GitHub Desktop.
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