Ruby - rails - how to create automatic hyperlinks for URLs in the text / string rendered on the view?

advertisements

How to create automatic hyperlinks for urls in the text/string rendered on the view? I have a page that renders user activity log and in that log/text/string there are some random urls which I want to automatically hyperlink to open in a new browser window. There is this auto_link in ruby rails, how do I use that?

text = "User xyz accessed url - http://www.something.com on 04/13/2012 00:13:18GMT"

<%= "#{Text}" %>

I want this rendered with a hyperlink to the url. The URL could be anything anywhere in the text.


Use auto_link like this:

<%= auto_link(text) %>

If you want the generated links to open new browser windows (or tabs) add the option like so:

<%= auto_link(text, :html => { :target => '_blank' }) %>

As mentioned by pjumble in the comments, auto_link is no longer a part of Rails core as of Rails 3.1, this gem brings it back: https://github.com/tenderlove/rails_autolink Thanks pjumble!