lib/dry/schema/message_compiler.rb in dry-schema-1.4.3 vs lib/dry/schema/message_compiler.rb in dry-schema-1.5.0
- old
+ new
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-require 'dry/initializer'
+require "dry/initializer"
-require 'dry/schema/constants'
-require 'dry/schema/message'
-require 'dry/schema/message_set'
-require 'dry/schema/message_compiler/visitor_opts'
+require "dry/schema/constants"
+require "dry/schema/message"
+require "dry/schema/message_set"
+require "dry/schema/message_compiler/visitor_opts"
module Dry
module Schema
# Compiles rule results AST into human-readable format
#
@@ -42,11 +42,11 @@
# @api private
def initialize(messages, **options)
super
@options = options
- @default_lookup_options = options[:locale] ? { locale: locale } : EMPTY_HASH
+ @default_lookup_options = options[:locale] ? {locale: locale} : EMPTY_HASH
end
# @api private
def with(new_options)
return self if new_options.empty?
@@ -99,20 +99,32 @@
left
end
end
# @api private
+ def visit_unexpected_key(node, _opts)
+ path, input = node
+
+ msg = messages.translate("errors.unexpected_key")
+
+ Message.new(
+ path: path,
+ text: msg[:text],
+ predicate: nil,
+ input: input
+ )
+ end
+
+ # @api private
def visit_or(node, opts)
left, right = node.map { |n| visit(n, opts) }
+ Message::Or[left, right, or_translator]
+ end
- if [left, right].flatten.map(&:path).uniq.size == 1
- Message::Or.new(left, right, proc { |k| messages.translate(k, **default_lookup_options) })
- elsif right.is_a?(Array)
- right
- else
- [left, right].flatten.max
- end
+ # @api private
+ def or_translator
+ @or_translator ||= proc { |k| messages.translate(k, **default_lookup_options) }
end
# @api private
def visit_namespace(node, opts)
ns, rest = node
@@ -128,17 +140,25 @@
options = opts.dup.update(
path: path.last, **tokens, **lookup_options(arg_vals: arg_vals, input: input)
).to_h
- template, meta = messages[predicate, options] ||
- raise(MissingMessageError.new(path, messages.looked_up_paths(predicate, options)))
+ template, meta = messages[predicate, options]
+ unless template
+ raise MissingMessageError.new(path, messages.looked_up_paths(predicate, options))
+ end
+
text = message_text(template, tokens, options)
message_type(options).new(
- text: text, path: path, predicate: predicate, args: arg_vals, input: input, meta: meta
+ text: text,
+ meta: meta,
+ path: path,
+ predicate: predicate,
+ args: arg_vals,
+ input: input
)
end
# @api private
def message_type(*)
@@ -178,10 +198,10 @@
# @api private
def message_text(template, tokens, options)
text = template[template.data(tokens)]
- return text unless full
+ return text if !text || !full
rule = options[:path]
"#{messages.rule(rule, options) || rule} #{text}"
end