Sha256: d36e1d131d8aa581632c6aed997c1bca841a123a45b827c1e42920104ba47384

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

require "erb"
require "json"

module TerraformTemplateRenderer
  # Renderer to remder an ERB template with variables taken from a json string instead of
  # from the original binding
  class Renderer
    def initialize(template, template_path)
      # The third argument enables trim mode using a hyphen
      @erb_template = ERB.new(template, nil, "-")
      @template_path = template_path
    end

    # The passed in json_variables needs to be a JSON object (not array), all the keys will be used
    # as variables in the templates
    def render(json_variables)
      binding_ = template_binding(json_variables)
      render_with_binding(binding_)
    end

    def render_with_binding(binding_)
      @erb_template.result(binding_.bind)
    end

    private

    def template_binding(json_variables)
      Binding.new(@template_path).tap do |binding_object|
        add_params_to_object(binding_object, JSON.parse(json_variables))
      end
    end

    def add_params_to_object(object, params)
      params.each do |key, value|
        object.add_param(key, value)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
terraform-template-renderer-0.3.0 lib/terraform_template_renderer/renderer.rb