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:


validates :hours, :presence => true, :numericality => { :greater_than
=> 0, :less_than => 12 }

before_validation do
STDOUT << ‘Test’
self.hours = hours.scan( /(\d*):(\d*)/ ).map { |hrs, mins| hrs.to_f

  • ( mins.to_f / 60.0 ) }.first.round(4) if hours && hours =~ /:confused:
    end

The problem I’m getting is that the validation doesn’t appear to fire at
all.

When I input “:05”, for example.

The form states that Hours is not a number.
I don’t see “Test” in the server console.

The code converting from a time string into a float appears to work in
IRB.

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.


before_validation :convert_hours

protected

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


However, the validation that triggers:


validates :hours, :presence => true, :numericality => { :greater_than =>
0, :less_than => 12 }


States that Hours is not a number.

So where is this 0.0 coming from? Is it even possible to get this value
as a string if it’s a Decimal in the database?

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

On Tuesday, 25 June 2013 05:15:06 UTC-7, Ruby-Forum.com User wrote:

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 J.
end

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