Class: ServerSide::Template
Overview
The Template module implements an Erubis template rendering system. Templates are cached and automatically reloaded if the file changes.
Constant Summary collapse
- @@templates =
The @@templates variable caches templates in use. The values are arrays containing 2 objects: a file stamp (if the template comes from a file,) and the template object itself.
{}
Class Method Summary collapse
-
.render(name, binding) ⇒ Object
Renders a template by first validating it, and by invoking it with the supplied binding.
-
.set(name, body, stamp = nil) ⇒ Object
Caches a template for later use.
-
.validate(name) ⇒ Object
Validates the referenced template by checking its stamp.
Class Method Details
.render(name, binding) ⇒ Object
Renders a template by first validating it, and by invoking it with the supplied binding.
37 38 39 40 41 42 43 |
# File 'lib/serverside/template.rb', line 37 def self.render(name, binding) if template = validate(name) template.result(binding) else raise RuntimeError, 'Template not found.' end end |
.set(name, body, stamp = nil) ⇒ Object
Caches a template for later use. The stamp parameter is used only when the content of a template file is stored.
15 16 17 |
# File 'lib/serverside/template.rb', line 15 def self.set(name, body, stamp = nil) @@templates[name] = [stamp, Erubis::Eruby.new(body)] end |
.validate(name) ⇒ Object
Validates the referenced template by checking its stamp. If the name refers to a file, its stamp is checked against the cache stamp, and it is reloaded if necessary. The function returns an ERB instance or nil if the template is not found.
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/serverside/template.rb', line 23 def self.validate(name) t = @@templates[name] return t[1] if t && t[0].nil? if File.file?(name) stamp = File.mtime(name) t = set(name, IO.read(name), stamp) if (!t || (stamp != t[0])) t[1] else @@templates[name] = nil end end |