Created
March 16, 2010 19:44
-
-
Save levicole/334415 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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