ActiveRecord Reflective Validation

Posted by Chris Thu, 05 Jun 2008 06:55:00 GMT

So, this is a pretty basic “for work” thing I ran into.

Managers like forms with little red asterisks next to required fields, and there doesn’t seem to be any straightforward way to query an ActiveRecord class to determine which fields are required.

Since AR already has to perform the validation, it seemed only right to lump it with the responsibility of keeping track of its own details.

So far, I’ve knocked up a small plugin within an existing rails app, which currently deals with presence and uniqueness validations, by providing the methods:

  • validates_presence_of?(field)
  • validates_uniqueness_of?(field)

to inspect the model classes.

Without further ado, here’s the prototype code:

module ActiveRecord
  module ReflectiveValidation
    def self.included(mod)
      mod.extend ClassMethods
      validation_methods.each do |method|
        arr_name = "#{method}_fields".to_sym
        mod.class_inheritable_array(arr_name)
        mod.write_inheritable_array(arr_name, [])
      end
    end

    def self.validation_methods
      [
        :validates_presence_of,
        :validates_uniqueness_of
      ]
    end
    module ClassMethods
      ActiveRecord::ReflectiveValidation::validation_methods.each do |method|
        module_eval(
          <<-eos
            def #{method}(*fields)
              write_inheritable_array(:#{method}_fields, fields)
              super(fields)
            end

            def #{method}?(field)
              #{method}_fields.include?(field)
            end
          eos
        )
      end
    end
  end
end

I’m looking at fleshing it out, handling more validations, and hopefully dealing with things like length requirements.

Oh, and actually hosting the plugin somewhere.

Posted in  | Tags , , ,  | no comments