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
The problem is that
in your code assigns a new value to the
linkvariable withing the block, but doesn’t change the corresponding element of the list.To alter elements of the list in-place you can use
Array#map!:Another thing I’m a bit worried about is that
include?will return true even if the given substring (e.g.,'http://'occurs somewhere in the middle of your string and not necessarily at the beginning. I’d rather use a regexp for that task:Update
If
linkis an attribute of your model, then you should at least store it as an attribute and not as a locallinksvariable: