before_validation attribute modification

Try this:

class Product < ActiveRecord::Base

  validates_format_of :hs_class_code, :with => /\A(\d{6}|\d{8}|\d{10})?\Z/

  before_validation :clean_tariff_code

  protected

  def clean_tariff_code     self.hs_class_code.gsub!(".","") unless self.hs_class_code.nil?   end

It makes it more clear if you name the method. Also, it is a good idea to use self. to be sure that what are intended to be accessor method calls are not interpreted as local variables.

Another problem was the use of tr which returns nil if no substitution is made. The was your initial method was written, if hs_class_code did not contain the "." character, the result would be to call strip on nil.

Hope this helps -Bill

James Byrne wrote:

Well, I am not sure about :with on before_validation as I don’t see it in the docs or examples anywhere, but I’m not saying it won’t work, I just don’t know. What I can do is show you how I do it and others may chime in with alternatives / better solutions if some exist. First, what I think you are asking is how to generically call your clean method by passing in the attribute and the regex to use. Here are two ways, one more verbose than the other, but it’s more self documenting.

`before_validation :delouse_hs_class_code

before_validation :delouse_another_one

protected

def delouse_another_one

delouse(:another_one,/\"/)

end

def delouse_hs_class_code

delouse(:hs_class_code,/\./)

end

def delouse(attr,regex)

`

`self.send(attr).gsub!(regex,"") unless self.send(attr).nil?`

end

Or you could use Proc’s

before_validation ``Proc.new{|o| o.delouse(:hs_class_code,/\./)}

`before_validation Proc.new{|o| o.delouse(:another_one,/"/)}

``

protected

``

def delouse(attr,regex)

`

`self.send(attr).gsub!(regex,"") unless self.send(attr).nil?`

end

`

`

This should get you going in the right direction. This is just a mock up that I didn’t test exactly and this was also written before my first cup of coffee :slight_smile:

HTH,

-Bill

James Byrne wrote:

As for the regex, I agree, always use what you want to allow rather than attempting to guess everything you need to take out. In the examples, I was just using what you had in the original method. As far as passing options, you will need to use one of the 2 methods I presented, both of which will allow multiple arguments.

-Bill

James Byrne wrote: