Class: Object

Inherits:
BasicObject
Defined in:
lib/kitchen/patches/renderable.rb

Overview

Monkey patches for Object

Class Method Summary collapse

Class Method Details

.renderable(dir: nil) ⇒ Object

Adds a ‘render` method to a class for rendering an ERB template to a string.

Parameters:

  • dir (String) (defaults to: nil)

    a directory in which to find the template to be rendered, populated with a guess from the call stack if not provided.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/kitchen/patches/renderable.rb', line 11

def self.renderable(dir: nil)
  dir ||= begin
    this_patch_file = __FILE__
    this_patch_file_caller_index = caller_locations.find_index do |location|
      location.absolute_path == this_patch_file
    end

    location_that_called_renderable = caller_locations[(this_patch_file_caller_index || -1) + 1]
    File.dirname(location_that_called_renderable.path)
  end

  class_eval <<~METHOD, __FILE__, __LINE__ + 1
    def renderable_base_dir
      "#{dir}"
    end
  METHOD

  class_eval do
    def render(file:)
      file = File.absolute_path(file, renderable_base_dir)
      template = File.open(file, 'rb', &:read)
      ERB.new(template, trim_mode: '-').result(binding)
    end
  end
end