Module: Validatable

Included in:
ActiveLeopard::Base
Defined in:
lib/activeleopard/modules/validatable.rb

Instance Method Summary collapse

Instance Method Details

#validates(attribute, options) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/activeleopard/modules/validatable.rb', line 2

def validates(attribute, options)
  method_name = "validate_#{attribute}"

  define_method(method_name) do
    attr_val = self.send(attribute)

    if options[:presence]
      if attr_val.nil?
        errors[attribute] << "can't be blank"
      end
    end

    if options[:uniqueness]
      matching_obj = self.class.find_by(attribute => attr_val)

      unless matching_obj.nil? || matching_obj.id == self.id
        errors[attribute] << "must be unique"
      end
    end
  end

  self.validations << method_name
end