Friday, May 6, 2011

Passing a method to validates_format_of

I want to do this:

validates_format_of :email, :with => email_regex

def email_regex
  email_name_regex  = '[A-Z0-9_\.%\+\-]+'
  domain_head_regex = '(?:[A-Z0-9\-]+\.)+'
  domain_tld_regex  = '(?:[A-Z]{2,4}|museum|travel)'
  return /\A#{email_name_regex}@#{domain_head_regex}#{domain_tld_regex}\z/i
end

but I am getting an error saying that I have to pass a regex to the validates method. I was sure youo could do something like this. Am I missing a step?

Thanks

From stackoverflow
  • What about just using a contstant? This would also ensure that the regexp gets only compiled once.

    class ...
      FOO_BAR = /#{baz}.../
    
      validatess ... :with => FOO_BAR
    

    but yeah, I'm not sure why your way doesn't work.

  • Your code looks OK. And I guess you define email_regex method before it is used by the validates method.

    You have to debug what validates_format_of gets (modify RoR code to print the :with argument type). This should be quite easy and help you solve the problem.

    Now I can only guess that email_regex method is redefined somewhere and returns something else than Regexp.

0 comments:

Post a Comment