This question has answered the question for a single column but how do you do it for multiple columns? I've got three columns (website, fb, twitter) that I want to prefix with http in case users don't input them in the form.
I tried this but it doesn't work:
before_save :sanitize_links
private
def sanitize_links
website = self.website
facebook = self.facebook
twitter = self.twitter
links = [website, facebook, twitter]
links.each do |link|
unless link.include?("http://") || link.include?("https://")
link = "http://" + link
end
end
end
Update
I've tried the suggestion by KL-7 but unfortunately hit a little snag. How do I use the output of the array with before_save
? I've tried the code below but it doesn't work.
before_save :sanitize_links
private
def sanitize_links
links = ["website", "facebook", "twitter"]
links.map! { |link| self.link =~ %r{\Ahttps?://} ? self.link : "http://" + self.link }
end
Update 2
I gave up. I'll just repeat it three times:
before_save :sanitize_links
private
def sanitize_links # prefix user-submitted links with http:// if missing
self.website =~ %r{\Ahttps?://} ? self.website : self.website = "http://" + self.website
self.facebook =~ %r{\Ahttps?://} ? self.facebook : self.facebook = "http://" + self.facebook
self.twitter =~ %r{\Ahttps?://} ? self.twitter : self.twitter = "http://" + self.twitter
end