Class: OsCtld::ErbTemplate

Inherits:
Object
  • Object
show all
Defined in:
lib/osctld/erb_template.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, vars) ⇒ ErbTemplate

Returns a new instance of ErbTemplate



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/osctld/erb_template.rb', line 28

def initialize(name, vars)
  @_tpl = ERB.new(File.new(OsCtld.tpl(name)).read, 0, '-')

  vars.each do |k, v|
    if v.is_a?(Proc)
      define_singleton_method(k, &v)
    elsif v.is_a?(Method)
      define_singleton_method(k) { |*args| v.call(*args) }
    else
      define_singleton_method(k) { v }
    end
  end
end

Class Method Details

.render(name, vars) ⇒ Object



6
7
8
9
# File 'lib/osctld/erb_template.rb', line 6

def self.render(name, vars)
  t = new(name, vars)
  t.render
end

.render_to(name, vars, path) ⇒ Object



11
12
13
14
# File 'lib/osctld/erb_template.rb', line 11

def self.render_to(name, vars, path)
  File.write("#{path}.new", render(name, vars))
  File.rename("#{path}.new", path)
end

.render_to_if_changed(name, vars, path) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/osctld/erb_template.rb', line 16

def self.render_to_if_changed(name, vars, path)
  tmp_path = "#{path}.new"
  File.write(tmp_path, render(name, vars))

  if !File.exist?(path) || !FileUtils.identical?(path, tmp_path)
    File.rename(tmp_path, path)

  else
    File.unlink(tmp_path)
  end
end

Instance Method Details

#renderObject



42
43
44
# File 'lib/osctld/erb_template.rb', line 42

def render
  @_tpl.result(binding)
end