Re: Validating DateHelpers date_select

Dee Zsombor
Thu, 26 May 2005 14:32:55 -0000

This snippet has a small bug: 18.years is still hard coded, you should
write age.years. Also I would inspect if generalization is worthwhile
at all ... do you have a constraint at application level for people
under 23 years? Or perhaps I''m just too lazy doing framework stuff ;-)

> validates_older_than :birthdate, :age => 18
>
> module ActiveRecord
>   module Validations
>     module ClassMethods
>       def validates_older_than(*attr_names)
>         configuration = { :message => "must be over %d" }
>         configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
>         min_age = configuration[:age].to_i
>         validate_each (attr_names, configuration) do |record, attr_name,
> value|
>           record.errors.add(attr_name, configuration[:message] % min_age)
> unless Time.now - value < 18.years
>         end
>       end
>     end
>   end
> end

--