user35288
user35288

Reputation:

Ruby on Rails regex

I have these statements in a model:

before_save :add_http

protected
def add_http
  if (/^http\:\/\/.+$/.match(url)) == nil
    str = "http://" + url
    url = str
  end
end

I have checked the regex in the console and it appears to be right, but when the 'url' gets saved to the db the "http://" has not been added. Any ideas?

Upvotes: 2

Views: 3365

Answers (2)

Sarah Mei
Sarah Mei

Reputation: 18484

Not sure if this matters to you or not, but your regex won't work with https URLs. This should work though:

def add_http
  self.url += "http://" if self.url.match(/^https?\:\/\/.+$/).nil?
end

Upvotes: 2

user35288
user35288

Reputation:

Nevermind, got it...

protected
def add_http
  if (/^http\:\/\/.+$/.match(url)) == nil
    str = "http://" + url
    self.url = str
  end
end

Upvotes: 2

Related Questions