Class: Broi::Errors

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/broi/errors.rb

Overview

TODO: Separate gem?

Instance Method Summary collapse

Constructor Details

#initialize(error_hash = {}) ⇒ Errors

Returns a new instance of Errors.



6
7
8
# File 'lib/broi/errors.rb', line 6

def initialize(error_hash = {})
  @errors = errorize_hash(error_hash)
end

Instance Method Details

#[](key) ⇒ Object



34
35
36
37
38
39
# File 'lib/broi/errors.rb', line 34

def [](key)
  key, nested = key.to_s.split('.', 2)
  return unless (result = @errors[key.to_sym])
  return result unless nested
  result[nested]
end

#each(&block) ⇒ Object



30
31
32
# File 'lib/broi/errors.rb', line 30

def each(&block)
  to_flat_hash.each(&block)
end

#to_flat_hashObject



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/broi/errors.rb', line 16

def to_flat_hash
  result = {}
  @errors.each do |key, value|
    if value.respond_to?(:to_flat_hash)
      value.to_flat_hash.each do |inner_key, inner_value|
        result[:"#{key}.#{inner_key}"] = inner_value.dup
      end
    else
      result[key] = value.dup
    end
  end
  result
end

#to_nested_hashObject



10
11
12
13
14
# File 'lib/broi/errors.rb', line 10

def to_nested_hash
  Broi::Input::Utils.deep_transform_values(@errors) do |value|
    value.respond_to?(:to_nested_hash) ? value.to_nested_hash : value
  end
end