I have a text area into which users enter a lot of text that potentially includes hyperlinks. How can I display the text and have the URLs automatically appear as hyperlinks? Is there a gem, plugin, or existing method that does this? I'm looking to be able to do something like:
<%=h @my_object.description.with_links %>
in my view.
Asked
Active
Viewed 7,600 times
13

Clay
- 2,949
- 3
- 38
- 54
-
with some extras: http://stackoverflow.com/questions/22442375/escape-non-html-tags-in-plain-text-convert-plain-text-to-html/22442376#22442376 – brauliobo Mar 16 '14 at 20:18
2 Answers
21
Rails 3
Use the provided helper method called auto_link
, which is part of ActionPack.
<%=h auto_link(@my_object.description) %>
Rails 4
Auto-linking has been removed from Rails and has been made into the rails_autolink
gem.
require 'rails_autolink'
auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com")
# => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
# say hello to <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"

JP Silvashy
- 46,977
- 48
- 149
- 227
-
You may be careful using this. It generates html_safe text. That means if you text to convert is something like : "hello
www.google.fr" you will get a surprise (and a security hole of course) – Marcel Falliere Apr 18 '11 at 21:39 -
To add to Marcel's comment the Sanitize gem can help with selective removal of HTML. – Kris Sep 19 '11 at 14:36
-
1Looks like its no longer available. The link that you have in your answer is not pointing to the right page. – Pratik Khadloya Oct 15 '12 at 18:52
-
2Removed from Rails 3.1 and packaged into [auto_link](https://github.com/tenderlove/rails_autolink) gem – hammady Oct 20 '13 at 07:06