Class: Okay::Template

Inherits:
Object show all
Includes:
WarningHelpers
Defined in:
lib/okay/template.rb

Overview

An extremely simple templating engine.

General usage:

template = Okay::Template.new("./templates")
puts template.apply("some_template.html", {"some_key": "some value"})
template.directory #=> "./templates"

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from WarningHelpers

#silence_warnings, #with_warnings

Constructor Details

#initialize(directory) ⇒ Template

Create an Okay::Templates object.

Parameters:

  • directory (String)

    Path of the directory containing the templates.



25
26
27
# File 'lib/okay/template.rb', line 25

def initialize(directory)
  @directory = directory
end

Instance Attribute Details

#directoryObject (readonly)

Returns the value of attribute directory.



19
20
21
# File 'lib/okay/template.rb', line 19

def directory
  @directory
end

Instance Method Details

#apply(template_name, data) ⇒ String

Apply the template referenced by template_name to data.

Parameters:

  • template_name (String)

    Name of the template to use, relative to @directory (as passed to #initialize).

  • data (Hash)

    Data to apply the template to.

Returns:

  • (String)

    Result of applying the template to data.



37
38
39
40
41
42
43
44
# File 'lib/okay/template.rb', line 37

def apply(template_name, data)
  template_file = Pathname.new(@directory).join(template_name)
  template = template_file.read

  # Silence warnings while applying the template, since we don't
  # generally care about unused keys.
  silence_warnings { Kernel.format(template, data) }
end