lib/dry/schema/message_set.rb in dry-schema-0.4.0 vs lib/dry/schema/message_set.rb in dry-schema-0.5.0

- old
+ new

@@ -27,17 +27,19 @@ initialize_placeholders! end # @api public def each(&block) + return self if empty? return to_enum unless block + messages.each(&block) end # @api public def to_h - messages_map + @to_h ||= messages_map end alias_method :to_hash, :to_h # @api public def [](key) @@ -49,25 +51,34 @@ self[key] || raise(KeyError, "+#{key}+ message was not found") end # @api private def empty? - messages.empty? + @empty ||= messages.empty? end + # @api private + def freeze + to_h + empty? + super + end + private # @api private def messages_map(messages = self.messages) + return EMPTY_HASH if empty? + messages.group_by(&:path).reduce(placeholders) do |hash, (path, msgs)| node = path.reduce(hash) { |a, e| a[e] } msgs.each do |msg| node << msg end - node.map!(&:to_s) + node.map!(&:dump) hash end end @@ -76,15 +87,17 @@ @paths ||= messages.map(&:path).uniq end # @api private def initialize_placeholders! - @placeholders = messages.map(&:path).uniq.reduce({}) do |hash, path| + return @placeholders = EMPTY_HASH if empty? + + @placeholders = paths.reduce(EMPTY_HASH.dup) do |hash, path| curr_idx = 0 last_idx = path.size - 1 node = hash - while curr_idx <= last_idx do + while curr_idx <= last_idx key = path[curr_idx] node = (node[key] || node[key] = curr_idx < last_idx ? {} : []) curr_idx += 1 end