-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkify.rb
15 lines (14 loc) · 980 Bytes
/
linkify.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# http://snippets.dzone.com/posts/show/7455, ported from http://snippets.dzone.com/posts/show/6156
@generic_URL_regexp = Regexp.new( '(^|[\n (\[{])([\w]+?://[\w]+[^ \"\n\r\t<]*)', Regexp::MULTILINE | Regexp::IGNORECASE )
@starts_with_www_regexp = Regexp.new( '(^|[\n (\[{])((www)\.[^ \"\t\n\r<]*)', Regexp::MULTILINE | Regexp::IGNORECASE )
@starts_with_ftp_regexp = Regexp.new( '(^|[\n (\[{])((ftp)\.[^ \"\t\n\r<]*)', Regexp::MULTILINE | Regexp::IGNORECASE )
@email_regexp = Regexp.new( '(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)', Regexp::IGNORECASE )
# NOTE: The linkify operation is not idempotent. Do not run it on text that has already been linkified!
def linkify( text )
s = text.to_s
s.gsub!( @generic_URL_regexp, '\1<a href="\2">\2</a>' )
s.gsub!( @starts_with_www_regexp, '\1<a href="http://\2">\2</a>' )
s.gsub!( @starts_with_ftp_regexp, '\1<a href="ftp://\2">\2</a>' )
s.gsub!( @email_regexp, '\1<a href="mailto:\2@\3">\2@\3</a>' )
s
end