Class: DeeplyValid::Validation
- Inherits:
-
Object
- Object
- DeeplyValid::Validation
- Defined in:
- lib/deeply_valid/validation.rb
Overview
The Validation lets us define validations using several different kinds of rules.
Instance Method Summary collapse
-
#initialize(rule = nil, &block) ⇒ Validation
constructor
The initializer defines the conditions that will satasfy this validation.
-
#valid?(data) ⇒ Boolean
Validate data of any rule type.
-
#valid_pattern?(data) ⇒ Boolean
Validate data by regexp.
-
#valid_structure?(data, fragment_rule = nil) ⇒ Boolean
Recursively validate a complex data structure For now, only hashes are supported.
Constructor Details
#initialize(rule = nil, &block) ⇒ Validation
The initializer defines the conditions that will satasfy this validation.
18 19 20 21 22 23 24 25 26 |
# File 'lib/deeply_valid/validation.rb', line 18 def initialize(rule = nil, &block) if rule.nil? && !block_given? raise "No validation rule specified" end @rule = rule @block = block end |
Instance Method Details
#valid?(data) ⇒ Boolean
Validate data of any rule type.
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/deeply_valid/validation.rb', line 82 def valid?(data) if @rule.kind_of?(Regexp) valid_pattern?(data) elsif @rule.kind_of?(Hash) valid_structure?(data) elsif @block @block.call(data) else data == @rule end end |
#valid_pattern?(data) ⇒ Boolean
Validate data by regexp
33 34 35 |
# File 'lib/deeply_valid/validation.rb', line 33 def valid_pattern?(data) !!(data =~ @rule) end |
#valid_structure?(data, fragment_rule = nil) ⇒ Boolean
Recursively validate a complex data structure For now, only hashes are supported.
Example Rules:
{ :key => /regexp/ }
{ :key => Validation.new { |d| d > 20 } }
{ :key => "literal" }
{ :key => { :key2 => /regexp/ }, :key2 => "literal" }
As you see, rules can be nested arbitrarily deep. The validaions work like you would expect.
{ :key => /[a-z]+/ } will validate { :key => "a" }
{ :key => /[a-z]+/ } will NOT validate { :key => 123 }
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/deeply_valid/validation.rb', line 58 def valid_structure?(data, fragment_rule = nil) (fragment_rule || @rule).all? do |k, v| if v.is_a?(Validation) v.valid?(data[k]) elsif v.is_a?(Regexp) !!(data[k] =~ v) elsif v.is_a?(Hash) valid_structure?(data[k], v) else data[k] == v end end end |