Class: DeeplyValid::Base
- Inherits:
-
Object
- Object
- DeeplyValid::Base
- 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
-
.[](name) ⇒ Validation
Retrieve a validation object.
-
.define(name, rule) ⇒ Object
Add or create a validation object.
- .structure(name = nil, &block) ⇒ Object
- .value(&block) ⇒ Object
Methods included from ValidationHelpers
Class Method Details
.[](name) ⇒ Validation
Retrieve a validation object
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
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 |