views:

43

answers:

2

For example,

User adds this "iamsmelly.com".

And if I add an href to this, the link would be

www.mywebsite.com/iamsmelly.com

Is there a way to make it absolute if its not prepended by an http:// ?

Or should I revert to jQuery for this?

+3  A: 

Probably a good place to handle this is in a before_save on your model. I'm not aware of a predefined helper (though auto_link comes somewhat close) but a relatively simple regexp should do the job:

class User < ActiveRecord::Base
   before_save :check_links
   def check_links
     self.link = "http://" + self.link unless self.link.match /^(https?|ftp):\/\//
   end
end
Jakub Hampl
Sorry, I'm slightly daft. How would you implement this before_save? and how?
Trip
I updated the answer to show how you implemented the `before_save`.
Jakub Hampl
You are AWESOME! :D
Trip
+2  A: 

I've looked for something similar before with no luck. I made a helper method like so:

def ensure_absolute(str_link)
  (str_link.include?("http://") || str_link.include?("https://")) ? str_link : ("http://"+str_link)
end
tybro0103