Sha256: 852122be54b37c4635fef1fe5a73f52f6c20c078855a913faf195244bf7da57d

Contents?: true

Size: 1.34 KB

Versions: 19

Compression:

Stored size: 1.34 KB

Contents

module Boxes
  # Representations of Packer templates.
  class Template
    include Boxes::Errors

    attr_reader :name, :template

    # Load a template with a given name.
    #
    # @param env [Boxes::Environment] the environment to source templates.
    # @param name [String] the name of the template.
    #
    # @return [Boxes::Template] a template instance.
    def initialize(env, name)
      fail(TemplateNotFoundError) unless env.available_templates.include?(name)

      @name = name
      @template = ''
      File.open(Boxes.config.working_dir + "templates/#{name}.erb") do |f|
        @template << f.read
      end
    end

    # Render the template.
    #
    # @param args [Hash] the values to set.
    #
    # @return [String] the rendered template.
    def render(args)
      ERB.new(template, nil, '-').result(ERBContext.new(args).get_binding)
    end

    # A context to render inside, to avoid polluting other classes.
    class ERBContext
      # Create a new context with a given hash of values.
      #
      # @params args [Hash] the values to substitute.
      def initialize(args = {})
        args.each_pair do |k, v|
          instance_variable_set('@' + k.to_s, v)
        end
      end

      # The binding which is passed to ERB.
      def get_binding # rubocop:disable Style/AccessorMethodName
        binding
      end
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
boxes-3.7.0 lib/boxes/template.rb
boxes-3.6.1 lib/boxes/template.rb
boxes-3.6.0 lib/boxes/template.rb
boxes-3.5.0 lib/boxes/template.rb
boxes-3.4.0 lib/boxes/template.rb
boxes-3.3.1 lib/boxes/template.rb
boxes-3.3.0 lib/boxes/template.rb
boxes-3.2.0 lib/boxes/template.rb
boxes-3.1.0 lib/boxes/template.rb
boxes-3.0.0 lib/boxes/template.rb
boxes-2.5.0 lib/boxes/template.rb
boxes-2.4.0 lib/boxes/template.rb
boxes-2.3.0 lib/boxes/template.rb
boxes-2.2.0 lib/boxes/template.rb
boxes-2.1.1 lib/boxes/template.rb
boxes-2.1.0 lib/boxes/template.rb
boxes-2.0.2 lib/boxes/template.rb
boxes-2.0.1 lib/boxes/template.rb
boxes-2.0.0 lib/boxes/template.rb