Is there a ruby ​​helper for creating absolute links from custom links if they are not absolute?

For instance,

The user adds this "iamsmelly.com".

And if I add a href link, the link is

www.mywebsite.com/iamsmelly.com

Is there a way to make it absolute when not appended with http: //?

Or do I need to fall back to jQuery for this?

+2


a source to share


2 answers


Probably a good place to do this is before_save

on your model. I don't know of a predefined helper (although it auto_link

comes close), but a relatively simple regex 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

      

+3


a source


I've searched for something like this before with no luck. I made a helper method like this:



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

      

+2


a source







All Articles