Class: Bosh::Agent::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/bosh_agent/template.rb

Defined Under Namespace

Classes: TemplateDataError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(block) ⇒ Template

Returns a new instance of Template.

Raises:

  • (ArgumentError)


13
14
15
16
17
18
# File 'lib/bosh_agent/template.rb', line 13

def initialize(block)
  raise ArgumentError unless block.arity == 1
  @block = block
  @block.call(self)
  raise TemplateDataError if @template_data.nil?
end

Class Method Details

.write(&block) ⇒ Object



9
10
11
# File 'lib/bosh_agent/template.rb', line 9

def self.write(&block)
  self.new(block).write
end

Instance Method Details

#dst(path) ⇒ Object



36
37
38
# File 'lib/bosh_agent/template.rb', line 36

def dst(path)
  @dst = path
end

#renderObject



40
41
42
43
# File 'lib/bosh_agent/template.rb', line 40

def render
  template = ERB.new(@template_data, 0, '%<>-')
  template.result(@block.binding)
end

#src(template_src) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/bosh_agent/template.rb', line 20

def src(template_src)
  case template_src
  when String
    if template_src.match(%r{\A/})
      template_path = template_src
    else
      template_base_dir = File.dirname(__FILE__)
      template_path = File.join(template_base_dir, template_src)
    end
    fh = File.new(template_path)
  when IO, StringIO
    fh = template_src
  end
  @template_data = fh.read
end

#writeObject



45
46
47
# File 'lib/bosh_agent/template.rb', line 45

def write
  File.open(@dst, 'w') { |fh| fh.write(self.render) }
end