Module: DataMapper::Validate::AutoValidate

Included in:
ClassMethods
Defined in:
lib/dm-validations/auto_validate.rb

Instance Method Summary collapse

Instance Method Details

#auto_generate_validations(property) ⇒ Object

Auto-generate validations for a given property. This will only occur if the option :auto_validation is either true or left undefined.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/dm-validations/auto_validate.rb', line 36

def auto_generate_validations(property)
  property.options[:auto_validation] = true unless property.options.has_key?(:auto_validation)
  return unless property.options[:auto_validation]

  # a serial property is allowed to be nil too, because the
  # value is set by the storage system
  opts = { :allow_nil => property.nullable? || property.serial? }
  opts[:context] = property.options[:validates] if property.options.has_key?(:validates)

  # presence
  unless opts[:allow_nil]
    validates_present property.name, opts
  end

  # length
  if property.type == String
    #len = property.length  # XXX: maybe length should always return a Range, with the min defaulting to 1
    len = property.options.fetch(:length, property.options.fetch(:size, DataMapper::Property::DEFAULT_LENGTH))
    if len.is_a?(Range)
      opts[:within] = len
    else
      opts[:maximum] = len
    end
    validates_length property.name, opts
  end

  # format
  if property.options.has_key?(:format)
    opts[:with] = property.options[:format]
    validates_format property.name, opts
  end

  # uniqueness validator
  if property.options.has_key?(:unique)
    value = property.options[:unique]
    if value.is_a?(Array) || value.is_a?(Symbol)
      validates_is_unique property.name, :scope => Array(value)
    elsif value.is_a?(TrueClass)
      validates_is_unique property.name
    end
  end

  # numeric validator
  if Integer == property.type
    opts[:integer_only] = true
    validates_is_number property.name, opts
  elsif BigDecimal == property.type || Float == property.type
    opts[:precision] = property.precision
    opts[:scale]     = property.scale
    validates_is_number property.name, opts
  else
    # We only need this in the case we don't already
    # have a numeric validator, because otherwise
    # it will cause duplicate validation errors
    unless property.custom?
      validates_is_primitive property.name, opts
    end
  end
end