Class: Typingpool::Template::Env

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

Overview

This subclass provides two utility methods to all templates: read, for including the text of another template, and render, for rendering another template. Read takes a relative path, documented below. Render is passed the same hash as the parent template, merged with an optional override hash, as documented below.

This subclass also makes it easier to use a hash as the top-level variable namespace when rendering ERB templates.

Instance Method Summary collapse

Constructor Details

#initialize(hash, template) ⇒ Env

Construtor. Takes a hash to be passed to the template and a template (ERB).



17
18
19
20
# File 'lib/typingpool/template/env.rb', line 17

def initialize(hash, template)
  @hash = hash
  @template = template
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, value = nil) ⇒ Object (protected)



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/typingpool/template/env.rb', line 64

def method_missing(key, value=nil)
  if value
    key = key.to_s.sub(/=$/, '')
    @hash[key.to_sym] = value
  end
  if @hash.has_key? key
    @hash[key]
  elsif @hash.has_key? key.to_s
    @hash[key.to_s]
  end
end

Instance Method Details

#get_bindingObject



49
50
51
# File 'lib/typingpool/template/env.rb', line 49

def get_binding
  binding()
end

#read(path) ⇒ Object

Method passed into each template. Takes a relative path and returns the text of the file at that path.

The relative path is resolved as in look_in above, with the following difference: the current directory and each parent directory of the active template is searched first, up to the root transcript directory (either Config#template, the built-in app template dir, or any dir that has been manually added to look_in).



31
32
33
# File 'lib/typingpool/template/env.rb', line 31

def read(path)
  @template.class.new(path, localized_look_in).read.strip
end

#render(path, hash = {}) ⇒ Object

Method passed into each template. Takes a reltive path and returns the rendered text of the ERB template at that path. Can also take an optional hash, which will be merged into the parent template’s hash and passed to the included template. If the optional hash it not passed, the parent template’s hash will be passed to the included template unmodified.

The relative path is resolved as described in the docs for Template::Env#read.



45
46
47
# File 'lib/typingpool/template/env.rb', line 45

def render(path, hash={})
  @template.class.new(path, localized_look_in).render(@hash.merge(hash)).strip
end