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



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

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.

Parameters:

  • source (String)

    the path on disk where the ERB template lives

  • options (Hash) (defaults to: {})

    a customizable set of options

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



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/omnibus/templating.rb', line 66

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

  # String value returned from #render_template_content
  result = render_template_content(source, variables)

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

  true
end

#render_template_content(source, variables = {}) ⇒ String

Render an erb template to a String variable.

Parameters:

  • source (String)

    the path on disk where the ERB template lives

  • options (Hash)

    a customizable set of options

Returns:

  • (String)


38
39
40
41
42
43
44
45
46
47
48
# File 'lib/omnibus/templating.rb', line 38

def render_template_content(source, variables = {})
  template = ERB.new(File.read(source), trim_mode: "-")
  struct =
    if variables.empty?
      Struct.new("Empty")
    else
      Struct.new(*variables.keys).new(*variables.values)
    end

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