Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 727
Majoris Avatar asked Apr 15 '12 00:04

Majoris


2 Answers

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!

like image 119
ctcherry Avatar answered Nov 13 '22 08:11

ctcherry


For faster parsing, try https://github.com/vmg/rinku

require 'rinku'
Rinku.auto_link(text, mode=:all, link_attr=nil, skip_tags=nil)

Also one often need more filters than just linking, for example Youtube embedded videos. For this use: https://github.com/dejan/auto_html

like image 30
lulalala Avatar answered Nov 13 '22 07:11

lulalala