Class: Dry::Validator

Inherits:
Object
  • Object
show all
Extended by:
Configurable
Defined in:
lib/dry/validator.rb,
lib/dry/validator/rules.rb,
lib/dry/validator/version.rb,
lib/dry/validator/processor.rb,
lib/dry/validator/rules/each.rb,
lib/dry/validator/rules/length.rb,
lib/dry/validator/rules/registry.rb,
lib/dry/validator/rules/embedded.rb,
lib/dry/validator/rules/presence.rb,
lib/dry/validator/attribute_extractor.rb

Overview

A simple, configurable, stand-alone validator

Examples:


User = Struct.new(:name)

user_validator = Dry::Validator.new(
  name: {
    presence: true
  }
)

user = User.new('')
user_validator.call(user)
  => {:name=>[{:code=>"presence", :options=>true}]}

Defined Under Namespace

Modules: AttributeExtractor, Processor, Rules

Constant Summary collapse

VERSION =
'0.1.0'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Object

Create a new validator

Parameters:

  • rules (Hash)

    or options

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :rules (Hash)

    Validation rules

  • :processor (Mixed)

    Validation processor


46
47
48
49
50
51
52
53
54
# File 'lib/dry/validator.rb', line 46

def initialize(options = {})
  if options.fetch(:rules, false)
    @rules = options.fetch(:rules, {})
    @processor = options.fetch(:processor, default_processor)
  else
    @rules = options
    @processor = default_processor
  end
end

Instance Attribute Details

#processorMixed (readonly)

Returns Validation processor.

Returns:

  • (Mixed)

    Validation processor


33
34
35
# File 'lib/dry/validator.rb', line 33

def processor
  @processor
end

#rulesHash (readonly)

Returns Rules hash.

Returns:

  • (Hash)

    Rules hash


31
32
33
# File 'lib/dry/validator.rb', line 31

def rules
  @rules
end

Instance Method Details

#call(subject) ⇒ Object Also known as: validate

Create a new validator

Parameters:

  • subject (Object)

    The subject to validate

Returns:

  • Dry::Validator


78
79
80
# File 'lib/dry/validator.rb', line 78

def call(subject)
  processor.call(self, subject)
end

#merge(other) ⇒ Object Also known as: <<

Create a new validator

Parameters:

Returns:

  • Dry::Validator


63
64
65
66
67
68
# File 'lib/dry/validator.rb', line 63

def merge(other)
  self.class.new(
    rules: rules.merge(other.rules),
    processor: processor
  )
end