Correct use of before_validation

I'm using Rails 3.2.13 with Ruby 2.0.0

I have a field in a form called "hours" which normally passes a numerical value.

However, my users also want the option to pass time values, like "01:15", "00:25", ":05", etc.

I've tried to allow for this sort of thing with the below code:

I've managed to get the event to fire now, but what I get from STDOUT is 0.0 So I guess that means I'm not receiving a string from input.

Catching that 0.0 value was the right direction to look in:

  def convert_hours     if hours_before_type_cast && hours_before_type_cast =~ /:confused:       hrs, mins = hours_before_type_cast.scan( /(\d*):(\d*)/ ).first       self.hours = BigDecimal( ( hrs.to_f + ( mins.to_f / 60.0 ) ), 4 )     end   end

A cleaner way to do this would be to override the setter for hours:

def hours=(value)

if value =~ /:confused:

converted_value = … # do the conversion here

super(converted_value)

else

super

end

end

As an upside, this means that setting hours will always return the correct value, even before the before_validation callback runs.

–Matt Jones

end

Thanks for the tip! If the call to "super" triggers the validation then that should be perfect.