Convert links to clickable links in Rails
When someone types in a URL in a comment or message, it’d be nice if it would turn itself into a clickable URL, wouldn’t it? It’s a simple idea, and conveniently, it has a simple solution. Here’s my approach.
Create a separate module and stick it in your lib/ directory. You know the drill. Then stick this code in it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | module RPH module LinkConverter def self.included(klass) klass.extend ClassMethods end module ClassMethods def convert_links_for(*columns) methods = [] columns.each do |column| define_method "converted_link_#{column}" do html = self[column].to_s html.gsub!(/\swww\./, ' http://www.').to_s html.gsub!(/((https?:\/\/|www\.)([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/, '<a href="\1">\1</a>') self[column] = html end methods << "converted_link_#{column}".to_sym end before_save *methods end end end end |
This allows you to pass several columns to the link converter, and before the content is saved, the links will be converted to clickable URLs. In your model, just include the module and specify the columns, like so:
1 2 3 4 | class Comment < ActiveRecord::Base include RPH::LinkConverter convert_links_for :body end |
I’ve also created a gist, so fork and improve!

Nicolás Hock Tuesday, 08 Jun, 2010 Posted at 08:55PM
So what would be the difference of using this and “autolink” ?
http://api.rubyonrails.org/classes/ActionView…
Ryan Tuesday, 08 Jun, 2010 Posted at 11:43PM
Ha, absolutely nothing. I had no idea that even existed. Thanks for the info!