Class: Dry::Validation::MessageSet

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/dry/validation/message_set.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(messages) ⇒ MessageSet

Returns a new instance of MessageSet.



14
15
16
17
18
19
# File 'lib/dry/validation/message_set.rb', line 14

def initialize(messages)
  @messages = messages
  @hints = {}
  @paths = map(&:path).uniq
  initialize_placeholders!
end

Instance Attribute Details

#hintsObject (readonly)

Returns the value of attribute hints.



8
9
10
# File 'lib/dry/validation/message_set.rb', line 8

def hints
  @hints
end

#messagesObject (readonly)

Returns the value of attribute messages.



8
9
10
# File 'lib/dry/validation/message_set.rb', line 8

def messages
  @messages
end

#pathsObject (readonly)

Returns the value of attribute paths.



8
9
10
# File 'lib/dry/validation/message_set.rb', line 8

def paths
  @paths
end

#placeholdersObject (readonly)

Returns the value of attribute placeholders.



8
9
10
# File 'lib/dry/validation/message_set.rb', line 8

def placeholders
  @placeholders
end

Class Method Details

.[](messages) ⇒ Object



10
11
12
# File 'lib/dry/validation/message_set.rb', line 10

def self.[](messages)
  new(messages.flatten)
end

Instance Method Details

#dumpObject



21
22
23
# File 'lib/dry/validation/message_set.rb', line 21

def dump
  root? ? to_a : to_h
end

#each(&block) ⇒ Object



33
34
35
36
# File 'lib/dry/validation/message_set.rb', line 33

def each(&block)
  return to_enum unless block
  messages.each(&block)
end

#empty?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/dry/validation/message_set.rb', line 25

def empty?
  messages.empty?
end

#root?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/dry/validation/message_set.rb', line 29

def root?
  !empty? && messages.all?(&:root?)
end

#to_aObject



68
69
70
# File 'lib/dry/validation/message_set.rb', line 68

def to_a
  to_h.values.flatten
end

#to_hObject Also known as: to_hash



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/dry/validation/message_set.rb', line 43

def to_h
  if root?
    { nil => map(&:to_s) }
  else
    group_by(&:path).reduce(placeholders) do |hash, (path, msgs)|
      node = path.reduce(hash) { |a, e| a[e] }

      msgs.each do |msg|
        node << msg
        msg_hints = hints[msg.index_path]

        if msg_hints
          node.concat(msg_hints)
          node.uniq!(&:signature)
        end
      end

      node.map!(&:to_s)

      hash
    end
  end
end

#with_hints!(hints) ⇒ Object



38
39
40
41
# File 'lib/dry/validation/message_set.rb', line 38

def with_hints!(hints)
  @hints.update(hints.group_by(&:index_path))
  self
end