lib/dry/validation/hint_compiler.rb in dry-validation-0.7.4 vs lib/dry/validation/hint_compiler.rb in dry-validation-0.8.0

- old
+ new

@@ -3,11 +3,11 @@ module Dry module Validation class HintCompiler < ErrorCompiler::Input include Dry::Equalizer(:messages, :rules, :options) - attr_reader :rules, :excluded + attr_reader :rules, :excluded, :cache TYPES = { none?: NilClass, bool?: TrueClass, str?: String, @@ -21,38 +21,46 @@ array?: Array }.freeze EXCLUDED = [:none?, :filled?, :key?].freeze + DEFAULT_OPTIONS = { name: nil, input: nil, message_type: :hint }.freeze + + EMPTY_MESSAGES = {}.freeze + def self.cache @cache ||= Concurrent::Map.new end def initialize(messages, options = {}) - super(messages, { name: nil, input: nil }.merge(options)) + super(messages, DEFAULT_OPTIONS.merge(options)) @rules = @options.delete(:rules) @excluded = @options.fetch(:excluded, EXCLUDED) @val_type = options[:val_type] + @cache = self.class.cache end + def hash + @hash ||= [messages, rules, options].hash + end + def with(new_options) + return self if new_options.empty? super(new_options.merge(rules: rules)) end def call - self.class.cache.fetch_or_store(hash) do - super(rules) - end + cache.fetch_or_store(hash) { super(rules) } end def visit_predicate(node) predicate, _ = node val_type = TYPES[predicate] return with(val_type: val_type) if val_type - return {} if excluded.include?(predicate) + return EMPTY_MESSAGES if excluded.include?(predicate) super end def visit_set(node) @@ -97,10 +105,10 @@ def visit_val(node) visit(node) end def visit_schema(node) - DEFAULT_RESULT + merge(node.rule_ast.map(&method(:visit))) end def visit_check(node) DEFAULT_RESULT end