Class: OsCtl::ExportFS::ErbTemplate

Inherits:
Object
  • Object
show all
Defined in:
lib/osctl/exportfs/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
41
# File 'lib/osctl/exportfs/erb_template.rb', line 28

def initialize(name, vars)
  path = File.join(OsCtl::ExportFS.root, 'templates', "#{name}.erb")
  @_tpl = ERB.new(File.new(path).read, trim_mode: '-')

  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/osctl/exportfs/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/osctl/exportfs/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/osctl/exportfs/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



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

def render
  @_tpl.result(binding)
end