How to prefix http to multiple columns' url input from users in Rails? -


this question has answered question single column how do multiple columns? i've got 3 columns (website, fb, twitter) want prefix http in case users don't input them in form.

i tried 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 |link| unless link.include?("http://") || link.include?("https://") link = "http://" + link end end end 

update

i've tried suggestion kl-7 unfortunately hit little snag. how use output of array before_save? i've tried code below 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 repeat 3 times:

before_save :sanitize_links private def sanitize_links # prefix user-submitted links 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

link = "http://" + link 

in code assigns new value link variable withing block, doesn't change corresponding element of list.

to alter elements of list in-place can use array#map!:

links.map! |link| link.include?("http://") || link.include?("https://") ? link : "http://" + link end 

another thing i'm bit worried include? return true if given substring (e.g., 'http://' occurs somewhere in middle of string , not @ beginning. i'd rather use regexp task:

links.map! { |link| link =~ %r{\ahttps?://} ? link : "http://" + link } 

update

if link attribute of model, should @ least store attribute , not local links variable:

self.links = links.map { |link| link =~ %r{\ahttps?://} ? link : "http://" + link } 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -