2

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I thought about that but wanted to get the basics working first. By the way, I read your blog about the 'pron star' fiasco, nice article!
2

Nevermind, got it...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.