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
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
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:
if hours_before_type_cast && hours_before_type_cast =~ /
hrs, mins = hours_before_type_cast.scan( /(\d*):(\d*)/ ).first
self.hours = BigDecimal( ( hrs.to_f + ( mins.to_f / 60.0 ) ), 4 )
A cleaner way to do this would be to override the setter for hours:
if value =~ /
converted_value = … # do the conversion here
As an upside, this means that setting hours will always return the correct value, even before the before_validation callback runs.
Thanks for the tip! If the call to "super" triggers the validation then
that should be perfect.