DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Make URL's In Text Clickable
Ruby port of http://snippets.dzone.com/posts/show/6156 . Regexp's have been factored out into instance variables for efficiency when calling the linkify method more than once. Also, improved linkification of addresses that start with "ftp" (PHP version uses "http://" URL scheme for these instead of having a separate pass to apply the "ftp://" scheme).
@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 ) 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





