Class: DeeplyValid::Base

Inherits:
Object
  • Object
show all
Includes:
ValidationHelpers
Defined in:
lib/deeply_valid/base.rb

Overview

By subclassing the base class, you can easily create groups of validations.

Example:

class Sample < DeeplyValid::Base
  define :regexp,     /[a-z]+/
  define :manual,     DeeplyValid::Validation.new { |d| d > 10 } 
  define :literal,    "x"
  define :structure,  { :key => "val" }
end

Sample[:literal].valid?("x") # will return true

Example using ValidationHelpers

class Sample < DeeplyValid::Base
  define :name,       string(1..128)
  define :age,        integer(1..70)
  define :children,   hash( token => integer )
  define :colors,     array(any(:red, green, :blue))  
end

Class Method Summary collapse

Methods included from ValidationHelpers

included

Class Method Details

.[](name) ⇒ Validation

Retrieve a validation object

Parameters:

  • the (Symbol)

    key used in ‘define`

Returns:



50
51
52
# File 'lib/deeply_valid/base.rb', line 50

def [](name)
  (@definitions ||= {})[name.to_sym]
end

.define(name, rule) ⇒ Object

Add or create a validation object

Parameters:

  • name (Symbol)

    A key that you’ll use to retrieve the Validation

  • rule

    Any validation rule accepted by ‘DeeplyValid::Validation.new`



40
41
42
# File 'lib/deeply_valid/base.rb', line 40

def define(name, rule)
  (@definitions ||= {})[name.to_sym] = rule.is_a?(Validation) ? rule : Validation.new(rule)
end

.structure(name = nil, &block) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/deeply_valid/base.rb', line 54

def structure(name = nil, &block)
  if name
    Validation.new { |d| self[name.to_sym].valid?(d) }
  elsif block_given?
    block
  else
    raise "structure requires name or block"
  end
end

.value(&block) ⇒ Object



64
65
66
# File 'lib/deeply_valid/base.rb', line 64

def value(&block)
  block
end