-
Notifications
You must be signed in to change notification settings - Fork 145
Linkify URLs
JasonBarnabe edited this page Feb 21, 2012
·
3 revisions
This transformer will turn plain text URLs into anchors.
def has_anchor_ancestor(node)
until node.nil?
return true if node.name == 'a'
node = node.parent
end
return false
end
def replace_text_with_link(node, original_text, link_text, url)
# the text itself becomes a link
link = Nokogiri::XML::Node.new('a', node.document)
link['href'] = url
link.add_child(Nokogiri::XML::Text.new(link_text, node.document))
return replace_text_with_node(node, original_text, link)
end
linkify_urls = lambda do |env|
node = env[:node]
return unless node.text?
return if has_anchor_ancestor(node)
url_reference = node.text.match(/(\s|^|\()(https?:\/\/[^\s\)\]]*)/i)
return if url_reference.nil?
resulting_nodes = replace_text_with_link(node, url_reference[2], url_reference[2], url_reference[2])
# sanitize the new nodes ourselves; they won't be picked up otherwise.
resulting_nodes.delete(node)
resulting_nodes.each do |new_node|
Sanitize.clean_node!(new_node, env[:config])
end
end