Class: MiniDefender::Rules::Hash

Inherits:
MiniDefender::Rule show all
Defined in:
lib/mini_defender/rules/hash.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from MiniDefender::Rule

#active?, available?, #bails?, #default_value, #defaults?, #error_message, #excluded?, #implicit?, #stops?, #with_message

Constructor Details

#initialize(data_mode = 'none', key_type = 'any', value_type = 'any') ⇒ Hash

Returns a new instance of Hash.



8
9
10
11
12
# File 'lib/mini_defender/rules/hash.rb', line 8

def initialize(data_mode = 'none', key_type = 'any', value_type = 'any')
  @data_mode = data_mode
  @key_type = key_type
  @value_type = value_type
end

Class Method Details

.make(args) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/mini_defender/rules/hash.rb', line 14

def self.make(args)
  new(
    args[0] || 'none',
    args[1] || 'any',
    args[2] || 'any',
  )
end

.signatureObject



4
5
6
# File 'lib/mini_defender/rules/hash.rb', line 4

def self.signature
  'hash'
end

Instance Method Details

#coerce(value) ⇒ Object



26
27
28
# File 'lib/mini_defender/rules/hash.rb', line 26

def coerce(value)
  @data_mode == 'all' ? value : {}
end

#force_coerce?Boolean

Returns:



30
31
32
# File 'lib/mini_defender/rules/hash.rb', line 30

def force_coerce?
  true
end

#message(attribute, value, validator) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/mini_defender/rules/hash.rb', line 59

def message(attribute, value, validator)
  additional = ''

  if @key_type != 'any'
    additional += ", key must be #{@key_type}"
  end

  if @value_type != 'any'
    additional += ", value must be #{@value_type}"
  end

  "The field must be an object#{additional}."
end

#passes?(attribute, value, validator) ⇒ Boolean

Returns:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/mini_defender/rules/hash.rb', line 34

def passes?(attribute, value, validator)
  passes = value.is_a?(Hash)

  unless passes
    return false
  end

  if @key_type == 'string'
    passes &= value.all? { |k, _| k.is_a?(String) }
  end

  case @value_type
    when 'string'
      passes &= value.all? { |_, v| v.is_a?(String) }
    when 'integer'
      passes &= value.all? { |_, v| v.is_a?(Integer) }
    when 'float'
      passes &= value.all? { |_, v| v.is_a?(Float) }
    else
      # None
  end

  passes
end

#priorityObject



22
23
24
# File 'lib/mini_defender/rules/hash.rb', line 22

def priority
  500
end