Sha256: 944b2f77de1905192dbc728872eaa4524777761f68a306e96b8c40ba0ec1d354

Contents?: true

Size: 971 Bytes

Versions: 13

Compression:

Stored size: 971 Bytes

Contents

class HashValidator::Validator::LambdaValidator < HashValidator::Validator::Base
  def initialize
    super('_lambda')  # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator)
  end

  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

  def presence_error_message
    'is not valid'
  end

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

  rescue
    errors[key] = presence_error_message
  end
end

class HashValidator::Validator::LambdaValidator::InvalidArgumentCount < StandardError
end

HashValidator.append_validator(HashValidator::Validator::LambdaValidator.new)

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
hash_validator-1.1.1 lib/hash_validator/validators/lambda_validator.rb
hash_validator-1.1.0 lib/hash_validator/validators/lambda_validator.rb
hash_validator-1.0.0 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.8.0 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.7.1 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.7.0 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.6.0 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.5.0 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.4.0 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.3.0 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.2.7 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.2.6 lib/hash_validator/validators/lambda_validator.rb
hash_validator-0.2.5 lib/hash_validator/validators/lambda_validator.rb