Skip to content

Instantly share code, notes, and snippets.

@brand-it
Created October 23, 2018 22:01
Show Gist options
  • Save brand-it/a94e21b5c56d4c5f7d0d1e6646102d86 to your computer and use it in GitHub Desktop.
Save brand-it/a94e21b5c56d4c5f7d0d1e6646102d86 to your computer and use it in GitHub Desktop.
class << self
protected
def gsub_text_nodes_only!(html:, placeholder_name:, placeholder_value:)
fragment = Nokogiri::HTML.fragment(html)
fragment.traverse do |node|
next unless node.text?
# Can't use normal gsub! because it makes a copy of the content memory that is not attached
# to the node. Have to use the setter provided by nokogiri to update the node
# https://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri%2FXML%2FNode:content=
node.content = gsub_placeholder!(
node.content,
placeholder_name: placeholder_name,
placeholder_value: placeholder_value,
)
end
# updates the orginal html with are new html
html.replace(fragment.to_html_preserve_space)
end
def gsub_placeholder!(text, placeholder_name:, placeholder_value:)
text.gsub!(/\{\{\s*#{placeholder_name}\s*\}\}/i, placeholder_value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment