Module: Omnibus::Templating

Included in:
Builder, Packager::Base
Defined in:
lib/omnibus/templating.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



21
22
23
24
# File 'lib/omnibus/templating.rb', line 21

def self.included(base)
  # This module also requires logging
  base.send(:include, Logging)
end

Instance Method Details

#render_template(source, options = {}) ⇒ Object

Render an erb template on disk at source. If the :destination option is given, the file will be rendered at :destination, otherwise the template is rendered next to source, removing the 'erb' extension of the template.

Options Hash (options):

  • :destination (String) — default: default: +source+

    the destination where the rendered ERB should reside

  • :mode (Fixnum) — default: default: +0644+

    the mode of the rendered file

  • :variables (Hash) — default: default: +{}+

    the list of variables to pass to the template



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/omnibus/templating.rb', line 42

def render_template(source, options = {})
  destination = options.delete(:destination) || source.chomp('.erb')

  mode      = options.delete(:mode) || 0644
  variables = options.delete(:variables) || {}

  log.info(log_key) { "Rendering `#{source}' to `#{destination}'" }

  unless options.empty?
    raise ArgumentError,
      "Unknown option(s): #{options.keys.map(&:inspect).join(', ')}"
  end

  template = ERB.new(File.read(source), nil, '-')

  struct =
    if variables.empty?
      Struct.new("Empty")
    else
      Struct.new(*variables.keys).new(*variables.values)
    end

  result   = template.result(struct.instance_eval { binding })

  File.open(destination, 'w', mode) do |file|
    file.write(result)
  end

  true
end