Class: Subvalid::ValidationResult
- Inherits:
-
Object
- Object
- Subvalid::ValidationResult
- Defined in:
- lib/subvalid/validation_result.rb
Instance Attribute Summary collapse
-
#children ⇒ Object
readonly
Returns the value of attribute children.
-
#errors ⇒ Object
readonly
Returns the value of attribute errors.
Instance Method Summary collapse
- #[](attribute) ⇒ Object
- #add_error(error) ⇒ Object
- #flatten(parent_attributes = []) ⇒ Object
-
#initialize ⇒ ValidationResult
constructor
A new instance of ValidationResult.
- #merge_child!(attribute, result) ⇒ Object
- #to_h ⇒ Object
- #valid? ⇒ Boolean
Constructor Details
#initialize ⇒ ValidationResult
Returns a new instance of ValidationResult.
5 6 7 8 |
# File 'lib/subvalid/validation_result.rb', line 5 def initialize @errors = [] @children = {} end |
Instance Attribute Details
#children ⇒ Object (readonly)
Returns the value of attribute children.
3 4 5 |
# File 'lib/subvalid/validation_result.rb', line 3 def children @children end |
#errors ⇒ Object (readonly)
Returns the value of attribute errors.
3 4 5 |
# File 'lib/subvalid/validation_result.rb', line 3 def errors @errors end |
Instance Method Details
#[](attribute) ⇒ Object
18 19 20 |
# File 'lib/subvalid/validation_result.rb', line 18 def [](attribute) children[attribute] end |
#add_error(error) ⇒ Object
14 15 16 |
# File 'lib/subvalid/validation_result.rb', line 14 def add_error(error) errors << error end |
#flatten(parent_attributes = []) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/subvalid/validation_result.rb', line 40 def flatten(parent_attributes=[]) # TODO make this more flexible than just hardcoded format flat_errors = errors.map{|error| if parent_attributes.empty? error else human_keys = parent_attributes.map{|a| a.to_s.gsub('_', ' ')} [human_keys.join(", "), error].join(": ") end } children.each do |attribute, child| flat_errors += child.flatten(parent_attributes + [attribute]) end flat_errors end |
#merge_child!(attribute, result) ⇒ Object
22 23 24 25 26 27 28 29 |
# File 'lib/subvalid/validation_result.rb', line 22 def merge_child!(attribute, result) child = children[attribute] if child child.merge!(result) else children[attribute] = result end end |
#to_h ⇒ Object
31 32 33 34 35 36 37 38 |
# File 'lib/subvalid/validation_result.rb', line 31 def to_h hash = {} hash[:errors] = errors.dup unless errors.empty? children.each do |attribute, child| hash[attribute] = child.to_h unless child.valid? end hash end |
#valid? ⇒ Boolean
10 11 12 |
# File 'lib/subvalid/validation_result.rb', line 10 def valid? errors.empty? && children.values.all?(&:valid?) end |