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.



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

def initialize(name, vars)
  @_tpl = ErbTemplateCache[name]

  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, **kwargs| v.call(*args, **kwargs) }
    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, perm: 0o644) ⇒ Object



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

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

.render_to_if_changed(name, vars, path, perm: 0o644) ⇒ Object



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

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

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

  else
    File.unlink(tmp_path)
    File.chmod(perm, path)
  end
end

Instance Method Details

#renderObject



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

def render
  @_tpl.result(binding)
end