Class: HashValidator::Validator::LambdaValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/hash_validator/validators/lambda_validator.rb

Defined Under Namespace

Classes: InvalidArgumentCount

Instance Attribute Summary

Attributes inherited from Base

#name

Instance Method Summary collapse

Constructor Details

#initializeLambdaValidator

Returns a new instance of LambdaValidator.



2
3
4
# File 'lib/hash_validator/validators/lambda_validator.rb', line 2

def initialize
  super('_lambda')  # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator)
end

Instance Method Details

#presence_error_messageObject



18
19
20
# File 'lib/hash_validator/validators/lambda_validator.rb', line 18

def presence_error_message
  'is not valid'
end

#should_validate?(rhs) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
9
10
11
12
13
14
15
16
# File 'lib/hash_validator/validators/lambda_validator.rb', line 6

def should_validate?(rhs)
  if rhs.is_a?(Proc)
    if rhs.arity == 1
      true
    else
      raise HashValidator::Validator::LambdaValidator::InvalidArgumentCount.new("Lambda validator should only accept one argument, supplied lambda accepts #{rhs.arity}.")
    end
  else
    false
  end
end

#validate(key, value, lambda, errors) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/hash_validator/validators/lambda_validator.rb', line 22

def validate(key, value, lambda, errors)
  unless lambda.call(value)
    errors[key] = presence_error_message
  end

rescue
  errors[key] = presence_error_message
end