Skip to content

Instantly share code, notes, and snippets.

@levicole
Created March 16, 2010 19:44
Show Gist options
  • Select an option

  • Save levicole/334415 to your computer and use it in GitHub Desktop.

Select an option

Save levicole/334415 to your computer and use it in GitHub Desktop.
AUTO_LINK_RE = %r{
( https?:// | www\. )
[^\s<]+
}x unless const_defined?(:AUTO_LINK_RE)
BRACKETS = { ']' => '[', ')' => '(', '}' => '{' }
# Turns all urls into clickable links. If a block is given, each url
# is yielded and the result is used as the link text.
def auto_link_urls(text, html_options = {})
link_attributes = html_options.stringify_keys
text.gsub(AUTO_LINK_RE) do
href = $&
punctuation = ''
left, right = $`, $'
# detect already linked URLs and URLs in the middle of a tag
if left =~ /<[^>]+$/ && right =~ /^[^>]*>/
# do not change string; URL is alreay linked
href
else
# don't include trailing punctuation character as part of the URL
if href.sub!(/[^\w\/-]$/, '') and punctuation = $& and opening = BRACKETS[punctuation]
if href.scan(opening).size > href.scan(punctuation).size
href << punctuation
punctuation = ''
end
end
link_text = block_given?? yield(href) : href
href = 'http://' + href unless href.index('http') == 0
content_tag(:a, h(link_text), link_attributes.merge('href' => href)) + punctuation
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment