Sha256: b7a22b9ea0f1d0b14bccc6462a8682ecabd3ba2ce27bd51af6bae06e92ca74c4
Contents?: true
Size: 1.53 KB
Versions: 2
Compression:
Stored size: 1.53 KB
Contents
require 'dry/equalizer' 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) TOKEN_REGEXP = /%{([\w\d]*)}/ # !@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)) 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)] end # @api private def initialize(text, tokens, evaluator) @text = text @tokens = tokens @evaluator = evaluator end # @api private def data(input) tokens.each_with_object({}) { |k, h| h[k] = input[k] } end # @api private def call(data = EMPTY_HASH) data.empty? ? evaluator.() : evaluator.(data) end alias_method :[], :call end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
dry-schema-0.2.0 | lib/dry/schema/messages/template.rb |
dry-schema-0.1.1 | lib/dry/schema/messages/template.rb |