lib/dry/schema/message.rb in dry-schema-1.4.3 vs lib/dry/schema/message.rb in dry-schema-1.5.0

- old
+ new

@@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'dry/initializer' -require 'dry/equalizer' +require "dry/initializer" +require "dry/equalizer" -require 'dry/schema/path' -require 'dry/schema/message/or' +require "dry/schema/path" +require "dry/schema/message/or" module Dry module Schema # Message objects used by message sets # @@ -50,14 +50,27 @@ # # @return [String,Hash] # # @api public def dump - @dump ||= meta.empty? ? text : { text: text, **meta } + @dump ||= meta.empty? ? text : {text: text, **meta} end - alias to_s dump + alias_method :to_s, :dump + # Dump the message into a hash + # + # The hash will be deeply nested if the path's size is greater than 1 + # + # @see Message#to_h + # + # @return [Hash] + # + # @api public + def to_h + @to_h ||= _path.to_h(dump) + end + # See if another message is the same # # If a string is passed, it will be compared with the text # # @param other [Message,String] @@ -67,21 +80,34 @@ # @api private def eql?(other) other.is_a?(String) ? text == other : super end + # @api private + def to_or(root) + clone = dup + clone.instance_variable_set("@path", path - root.to_a) + clone.instance_variable_set("@_path", nil) + clone + end + # See which message is higher in the hierarchy # # @api private def <=>(other) - l_path = Path[path] - r_path = Path[other.path] + l_path = _path + r_path = other._path unless l_path.same_root?(r_path) - raise ArgumentError, 'Cannot compare messages from different root paths' + raise ArgumentError, "Cannot compare messages from different root paths" end l_path <=> r_path + end + + # @api private + def _path + @_path ||= Path[path] end end end end