Skip to content

Linkify URLs

Jason Barnabe edited this page · 3 revisions

This transformer will turn plain text URLs into anchors.

def has_ancestor(node, ancestor_node_name)
    until node.nil?
        return true if == ancestor_node_name
        node = node.parent
    return false

def replace_text_with_link(node, original_text, link_text, url)
    # the text itself becomes a link
    link ='a', node.document)
    link['href'] = url
    link.add_child(, node.document))
    return replace_text_with_node(node, original_text, link)

linkify_urls = lambda do |env|
    node = env[:node]
    return unless node.text?
    return if has_ancestor(node, 'a')
    return if has_ancestor(node, 'pre')
    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])
    # not required in Sanitize 3
    # 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
Something went wrong with that request. Please try again.