class Grizzled::String::Template::TemplateBase
Base (abstract) class for a string template. Common logic is here. Subclasses implement specific methods.
Attributes
Public Class Methods
Initializer.
Parameters:
resolver
-
A hash-like object that can take a variable name (via the +[]+ function) and resolve its value, returning the value (which is converted to string) or
nil
. options
-
hash of options. See below.
Options:
:safe
-
true
for a safe template that substitutes a blank string for a non-existent variable, instead of throwing an exception. Defaults totrue
.
# File lib/grizzled/string/template.rb, line 94 def initialize(resolver, options={}) @resolver = resolver @safe = options.fetch(:safe, true) end
Public Instance Methods
Parse the location of the first variable in the string. Subclasses should override this method.
Parameters:
s
-
the string
Returns a Variable
object, or nil
.
# File lib/grizzled/string/template.rb, line 141 def find_variable_ref(s) nil end
Get a variable's value, returning the empty string or throwing an
exception, depending on the setting of safe
.
Parameters:
name
-
Variable name
default
-
Default value, or
nil
# File lib/grizzled/string/template.rb, line 152 def get_variable(name, default) def handle_no_value(default, name) if not default.nil? default elsif @safe "" else raise VariableNotFoundException.new(name) end end resolver[name] || handle_no_value(default, name) end
# File lib/grizzled/string/template.rb, line 154 def handle_no_value(default, name) if not default.nil? default elsif @safe "" else raise VariableNotFoundException.new(name) end end
Replace all variable references in the given string. Variable references are recognized per the regular expression passed to the constructor. If a referenced variable is not found in the resolver, this method either:
-
throws a
VariableNotFoundException
(ifsafe
isfalse
). -
substitutes an empty string (if
safe
istrue
)
Recursive references are supported (but beware of infinite recursion).
Parameters:
s
-
the string in which to replace variable references
Returns the substituted result.
# File lib/grizzled/string/template.rb, line 114 def substitute(s) def substitute_variable(var, s) end_string = var.iend == s.length ? "" : s[var.iend..-1] value = get_variable(var.name, var.default) transformed = (var.istart == 0 ? "" : s[0..(var.istart-1)]) + value + end_string substitute(transformed) end # Locate the next variable reference. var = find_variable_ref(s) if var.nil? s else substitute_variable(var, s) end end
# File lib/grizzled/string/template.rb, line 116 def substitute_variable(var, s) end_string = var.iend == s.length ? "" : s[var.iend..-1] value = get_variable(var.name, var.default) transformed = (var.istart == 0 ? "" : s[0..(var.istart-1)]) + value + end_string substitute(transformed) end