Sha256: bbcef43b1456df68f388fdc9afd4c1a2d2f607e33479c80b9547e2b86de53b28

Contents?: true

Size: 1.13 KB

Versions: 5

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

require_relative 'string_template'

module Nocode
  module Util
    # Built on top of StringTemplate but instead of only working for a string, this will
    # recursively evaluate all strings within an object.  Heuristics:
    #    - Strings evaluate using StringTemplate
    #    - Hashes will have their keys and values traversed
    #    - Arrays will have their entries traversed
    #    - All other types will simply return themselves
    class ObjectTemplate
      attr_reader :object

      def initialize(object)
        @object = object

        freeze
      end

      def evaluate(values = {})
        recursive_evaluate(object, values)
      end

      private

      def recursive_evaluate(expression, values)
        case expression
        when Array
          expression.map { |o| recursive_evaluate(o, values) }
        when Hash
          expression.to_h do |k, v|
            [recursive_evaluate(k, values), recursive_evaluate(v, values)]
          end
        when String
          Util::StringTemplate.new(expression).evaluate(values)
        else
          expression
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
nocode-0.0.8 lib/nocode/util/object_template.rb
nocode-0.0.7 lib/nocode/util/object_template.rb
nocode-0.0.6 lib/nocode/util/object_template.rb
nocode-0.0.5 lib/nocode/util/object_template.rb
nocode-0.0.4 lib/nocode/util/object_template.rb