Module: Cure::Validators

Included in:
Strategy::BaseStrategyParams
Defined in:
lib/cure/validators.rb

Defined Under Namespace

Modules: Helpers

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.validatorsObject

Returns the value of attribute validators.



9
10
11
# File 'lib/cure/validators.rb', line 9

def validators
  @validators
end

Class Method Details

.common_validatorsObject



50
51
52
53
54
# File 'lib/cure/validators.rb', line 50

def common_validators
  {
    presence: proc { |current_val| !current_val.nil? }
  }
end

.instance_variables_hash(zelf) ⇒ Hash

Parameters:

  • zelf (Object)

Returns:

  • (Hash)


44
45
46
47
48
# File 'lib/cure/validators.rb', line 44

def instance_variables_hash(zelf)
  zelf.instance_variables.each_with_object({}) do |attribute, hash|
    hash[attribute] = zelf.instance_variable_get(attribute)
  end
end

.register_validator(caller, prop, options) ⇒ Object

Parameters:

  • prop (String)
  • options (Object)


13
14
15
16
# File 'lib/cure/validators.rb', line 13

def register_validator(caller, prop, options)
  @validators[caller] = [] unless @validators.has_key? caller
  @validators[caller] << {prop: "@#{prop}".to_sym, options:}
end

.validate(zelf) ⇒ TrueClass, FalseClass

Returns:

  • (TrueClass, FalseClass)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cure/validators.rb', line 19

def validate(zelf) # rubocop:disable Metrics/AbcSize
  return true unless @validators.has_key? zelf.class

  variables = instance_variables_hash(zelf)
  @validators[zelf.class].all? do |k|
    options = k[:options]
    return true if options.empty? # No validator, no need to run.

    validator_prop = options[:validator]
    proc = case validator_prop
           when Symbol
             common_validators.fetch(validator_prop, proc { |_x| false })
           # when Proc
           #   validator_prop
           else
             proc { |_x| false }
           end

    property = variables[k[:prop]]
    proc.call(property)
  end
end

Instance Method Details

#validates(property, options = {}) ⇒ Object



57
58
59
# File 'lib/cure/validators.rb', line 57

def validates(property, options={})
  Validators.register_validator(self, property, options)
end