How to DRY up validates_presence_of

Given the case of validating the presence of an attribute and then
performing other tests on said attribute, how do you go about not having
to check for nil in the other tests?

Example:

validates_presence_of :start_date, :end_date

validate :validate_start_date_before_end_date

def validate_start_date_before_end_date
# without this check an exception will be thrown on access to the
nil attribute
return if start_date.nil? || end_date.nil?

if end_date < start_date
  errors.add_to_base 'End date cannot be earlier than start date.'
end

end

Thanks.


Jack C.
[email protected]

On 7/17/06, Jack C. [email protected] wrote:

Given the case of validating the presence of an attribute and then
performing other tests on said attribute, how do you go about not having
to check for nil in the other tests?

I’m not sure if this is the correct answer but could you use a filter
to do extra validation after the main validation? I forget the order
but it seems like a before_save :validate_start_date_before_end_date
would do it. Any of [before_save, before_create, after_validation, and
after_validation_on_create] occur between validation and the final
save.

That said I don’t see much problem with repeating yourself on
occasion. I think it’s like the third-normal-form database thing; if
you have 18000 checks then checking if each is nil would be
terrifically annoying, but if not that extra .nil? might serve as
additional documentation adding clarity to the workflow.

Cheers,
Chuck V.