5

I'm building a simple chat app with Rails. when a user types in a url, I want it to be output as an html link (ie, "url").

I was wondering if there is any library or well known way to do this in Ruby. If not, I've got some decent regex sample code to work with...

1 Answer 1

10

Check out the auto_link helper method provided by Rails. This turns all URLs and email addresses into clickable links (html anchor tags). Here's a code sample from the docs.

auto_link("Go to http://www.rubyonrails.org and say hello to [email protected]")
# => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
#     say hello to <a href=\"mailto:[email protected]\">[email protected]</a>"
Sign up to request clarification or add additional context in comments.

4 Comments

awesome, thanks! so I could loop through every word in the message, if it passes the regex url test, render it as a link. I guess I'll have to figure out how to do this in the controller and not in a view. thanks again.
No need to loop through every word, If you pass the entire string to auto_link it should just link the urls and emails. Also, if you need to call this method outside of the view, check out this episode: railscasts.com/episodes/132-helpers-outside-views
This method has been removed from rails 3.1 but is available as a standalone gem 'rails_autolink' you could also look at the 'rinku' gem that offers performance benefits over the rails implementation.
Removed from Rails 3.1 and packaged into auto_link gem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.