Majoris
Majoris

Reputation: 3189

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.

Upvotes: 7

Views: 5456

Answers (2)

lulalala
lulalala

Reputation: 17981

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

Upvotes: 3

Chris Cherry
Chris Cherry

Reputation: 28554

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!

Upvotes: 13

Related Questions