Class: Lita::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/lita/template.rb

Overview

A simple wrapper around ERB to render text from files or strings.

Since:

  • 4.2.0

Defined Under Namespace

Classes: TemplateEvaluationContext

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Template

Returns a new instance of Template.

Parameters:

  • source (String)

    A string to use as the template's content.

Since:

  • 4.2.0


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

def initialize(source)
  @erb = ERB.new(source, trim_mode: "<>")
  self.helpers = Set.new
end

Class Method Details

.from_file(path) ⇒ Object

Initializes a new Template with the contents of the file at the given path.

Parameters:

  • path (String)

    The path to the file to use as the template content.

Returns:

  • Template

Since:

  • 4.2.0


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

def from_file(path)
  new(File.read(path).chomp)
end

Instance Method Details

#add_helper(helper) ⇒ void

This method returns an undefined value.

Add a module of helpers methods to be added to the template evalutation context.

Parameters:

  • helper (Module)

    The module to extend onto the template evalutation context.

Since:

  • 4.5.0


34
35
36
# File 'lib/lita/template.rb', line 34

def add_helper(helper)
  helpers << helper
end

#render(variables = {}) ⇒ Object

Render the template with the provided variables.

Parameters:

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

    A collection of variables for interpolation. Each key-value pair will make the value available inside the template as an instance variable with the key as its name.

Since:

  • 4.2.0


42
43
44
# File 'lib/lita/template.rb', line 42

def render(variables = {})
  erb.result(context_binding(variables))
end