Skip to content

Linkify URLs

Jason Barnabe edited this page Jun 26, 2014 · 3 revisions

This transformer will turn plain text URLs into anchors.

def has_ancestor(node, ancestor_node_name)
	until node.nil?
		return true if node.name == ancestor_node_name
		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_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
end