Class: Va::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/va.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Model

Returns a new instance of Model.



8
9
10
11
12
13
14
15
16
# File 'lib/va.rb', line 8

def initialize(args={})
  @attributes = {}
  args.each do |k, v|
    key = k.to_sym
    @attributes[key] = v if self.class.keys.include?(key)
  end
  @errors = {}
  @valid = validate
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



5
6
7
# File 'lib/va.rb', line 5

def attributes
  @attributes
end

#errorsObject (readonly)

Returns the value of attribute errors.



6
7
8
# File 'lib/va.rb', line 6

def errors
  @errors
end

Instance Method Details

#message(msg = "", *attrs) ⇒ Object



28
29
30
# File 'lib/va.rb', line 28

def message(msg="", *attrs)
  raise __callee__.inspect
end

#valid?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/va.rb', line 32

def valid?
  @valid
end

#validateObject



18
19
20
21
22
23
24
25
26
# File 'lib/va.rb', line 18

def validate
  invalid_validations = self.class.validations.select { |attrs, msg, validation|
    is_invalid = !validation.call(*attrs.map { |attr| self.send(attr)})
    key = attrs.count == 1 ? attrs.first : attrs
    errors[key] = msg || "is invalid" if is_invalid
    is_invalid
  }
  invalid_validations.empty?
end