Class: AppKernel::Validation::Validator

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fun, &block) ⇒ Validator

Returns a new instance of Validator.



7
8
9
10
# File 'lib/appkernel/validation.rb', line 7

def initialize(fun, &block)
  @fun = fun
  @body = block
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



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

def errors
  @errors
end

Instance Method Details

#validate(vars = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/appkernel/validation.rb', line 12

def validate(vars = {})
  errors = {}
  scope = Object.new
  scope.extend @fun.mod
  for k,v in vars do
    val = case v
    when nil
      NilValue.new
    when Fixnum
      FixnumValue.new(v)
    when Symbol
      v
    when FalseClass
      FalseValue.new
    when TrueClass
      TrueValue.new
    else
      v.dup
    end
    unless Symbol === val
      val.extend Check
      val.instance_eval do
        @_add_validation_error = lambda {|message|
          errors[k] = message
        }
      end
    end
    scope.instance_variable_set("@#{k}", val)
  end      
  scope.instance_eval &@body if @body
  errors
end