Class: Lono::Template::Template

Inherits:
Object
  • Object
show all
Includes:
ERB::Util
Defined in:
lib/lono/template/template.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, block = nil, options = {}) ⇒ Template

Returns a new instance of Template.



16
17
18
19
20
21
22
23
24
# File 'lib/lono/template/template.rb', line 16

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

Instance Attribute Details

#nameObject (readonly)

Main template DSL methods are: source and variables

template "example-2" do
  source "example"
  variables(test: 1)
end


15
16
17
# File 'lib/lono/template/template.rb', line 15

def name
  @name
end

Instance Method Details

#buildObject



43
44
45
46
47
48
49
50
51
52
# File 'lib/lono/template/template.rb', line 43

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.".colorize(:red)
    exit 1
  end
end

#contextObject

Context for ERB rendering. This is where we control what references get passed to the ERB rendering.



56
57
58
# File 'lib/lono/template/template.rb', line 56

def context
  @context ||= Lono::Template::Context.new(@options)
end

#default_source_path(name) ⇒ Object

internal methods



39
40
41
# File 'lib/lono/template/template.rb', line 39

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

#source(path) ⇒ Object

Returns path, example: ./app/templates/example.yml



27
28
29
30
# File 'lib/lono/template/template.rb', line 27

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

#variables(vars = {}) ⇒ Object



32
33
34
35
36
# File 'lib/lono/template/template.rb', line 32

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