Class: Validation::Rule::Type

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

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Type

Returns a new instance of Type.



5
6
7
8
9
10
11
# File 'lib/validation/rule/type.rb', line 5

def initialize(params = {})
  if params.is_a?(Hash)
    @params = params
  else
    @params = { classes: params }
  end
end

Instance Method Details

#error_keyObject



13
14
15
# File 'lib/validation/rule/type.rb', line 13

def error_key
  :type_rule
end

#paramsObject



40
41
42
# File 'lib/validation/rule/type.rb', line 40

def params
  @params
end

#valid_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
25
26
27
# File 'lib/validation/rule/type.rb', line 17

def valid_value?(value)
  return true if value.nil? && !params[:required]
  
  valid = true
  if params[:array]
    valid = false unless value.all? {|v| validate_type(v) }
  else
    valid = false unless validate_type(value)
  end
  valid
end

#validate_type(value) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/validation/rule/type.rb', line 29

def validate_type(value)
  valid = true
  case params[:classes]
  when Array
    valid = false unless params[:classes].any? {|type| value.is_a?(type) }
  else
    valid = false unless value.is_a?(params[:classes])
  end
  valid
end