Sha256: 917186560a963fb58b408bf1fa5a09a174c5429998d59938602457c04cf49475

Contents?: true

Size: 1.53 KB

Versions: 3

Compression:

Stored size: 1.53 KB

Contents

require 'erb'
require 'json'
require 'base64'

class Lono::Template::Template
  include ERB::Util

  # Main template DSL methods are: source and variables
  #
  #   template "example-2" do
  #     source "example"
  #     variables(test: 1)
  #   end
  #
  attr_reader :name
  def initialize(name, block=nil, options={})
    # Taking care to name instance variables with _ in front because we load the
    # variables from config/variables and those instance variables can clobber these
    # instance variables
    @name = name
    @block = block
    @options = options
    @source_path = default_source_path(name)
  end

  # Returns path, example: ./app/templates/example.yml
  def source(path)
    @source_path = path[0..0] == '/' ? path : "#{Lono.config.templates_path}/#{path}"
    @source_path += ".yml"
  end

  def variables(vars={})
    vars.each do |var,value|
      context.instance_variable_set("@#{var}", value)
    end
  end

  # internal methods
  def default_source_path(name)
    "#{Lono.config.templates_path}/#{name}.yml" # defaults to name, source method overrides
  end

  def build
    instance_eval(&@block) if @block

    if File.exist?(@source_path)
      RenderMePretty.result(@source_path, context: context)
    else
      puts "ERROR: #{@source_path} does not exist, but it was used as a template source.".color(:red)
      exit 1
    end
  end

  # Context for ERB rendering.
  # This is where we control what references get passed to the ERB rendering.
  def context
    @context ||= Lono::Template::Context.new(@options)
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lono-4.2.7 lib/lono/template/template.rb
lono-4.2.6 lib/lono/template/template.rb
lono-4.2.5 lib/lono/template/template.rb