lib/dry/schema/messages/template.rb in dry-schema-1.4.3 vs lib/dry/schema/messages/template.rb in dry-schema-1.5.0

- old
+ new

@@ -1,68 +1,43 @@ # frozen_string_literal: true -require 'dry/equalizer' +require "dry/initializer" +require "dry/equalizer" -require 'dry/schema/constants' +require "dry/schema/constants" module Dry module Schema module Messages - # Template wraps a string with interpolation tokens and defines evaluator function - # dynamically - # # @api private class Template - include Dry::Equalizer(:text) + extend Dry::Initializer + include Dry::Equalizer(:messages, :key, :options) - TOKEN_REGEXP = /%{(\w*)}/ + option :messages + option :key + option :options - # !@attribute [r] text - # @return [String] - attr_reader :text - - # !@attribute [r] tokens - # @return [Hash] - attr_reader :tokens - - # !@attribute [r] evaluator - # @return [Proc] - attr_reader :evaluator - # @api private - def self.[](input) - new(*parse(input)) + def data(data = EMPTY_HASH) + ensure_message! + messages.interpolatable_data(key, options, **options, **data) end # @api private - def self.parse(input) - tokens = input.scan(TOKEN_REGEXP).flatten(1).map(&:to_sym) - text = input.gsub('%', '#') - - evaluator = <<-RUBY.strip - -> (#{tokens.map { |token| "#{token}:" }.join(", ")}) { "#{text}" } - RUBY - - [text, tokens, eval(evaluator, binding, __FILE__, __LINE__ - 3)] + def call(data = EMPTY_HASH) + ensure_message! + messages.interpolate(key, options, **data) end + alias_method :[], :call - # @api private - def initialize(text, tokens, evaluator) - @text = text - @tokens = tokens - @evaluator = evaluator - end + private - # @api private - def data(input) - tokens.each_with_object({}) { |k, h| h[k] = input[k] } - end + def ensure_message! + return if messages.key?(key, options) - # @api private - def call(data = EMPTY_HASH) - data.empty? ? evaluator.() : evaluator.(**data) + raise KeyError, "No message found for template, template=#{inspect}" end - alias_method :[], :call end end end end