Class: Porthole::Template
- Inherits:
-
Object
- Object
- Porthole::Template
- Defined in:
- lib/porthole/template.rb
Overview
A Template represents a Porthole template. It compiles and caches a raw string template into something usable.
The idea is this: when handed a Porthole template, convert it into a Ruby string by transforming Porthole tags into interpolated Ruby.
You shouldn’t use this class directly, instead:
>> Porthole.render(template, hash)
Instance Attribute Summary collapse
-
#source ⇒ Object
readonly
Returns the value of attribute source.
Instance Method Summary collapse
-
#compile(src = @source) ⇒ Object
(also: #to_s)
Does the dirty work of transforming a Porthole template into an interpolation-friendly Ruby string.
-
#initialize(source) ⇒ Template
constructor
Expects a Porthole template as a string along with a template path, which it uses to find partials.
-
#render(context) ⇒ Object
Renders the ‘@source` Porthole template using the given `context`, which should be a simple hash keyed with symbols.
-
#tokens(src = @source) ⇒ Object
Returns an array of tokens for a given template.
Constructor Details
#initialize(source) ⇒ Template
Expects a Porthole template as a string along with a template path, which it uses to find partials.
22 23 24 |
# File 'lib/porthole/template.rb', line 22 def initialize(source) @source = source end |
Instance Attribute Details
#source ⇒ Object (readonly)
Returns the value of attribute source.
18 19 20 |
# File 'lib/porthole/template.rb', line 18 def source @source end |
Instance Method Details
#compile(src = @source) ⇒ Object Also known as: to_s
Does the dirty work of transforming a Porthole template into an interpolation-friendly Ruby string.
48 49 50 |
# File 'lib/porthole/template.rb', line 48 def compile(src = @source) Generator.new.compile(tokens(src)) end |
#render(context) ⇒ Object
Renders the ‘@source` Porthole template using the given `context`, which should be a simple hash keyed with symbols.
The first time a template is rendered, this method is overriden and from then on it is “compiled”. Subsequent calls will skip the compilation step and run the Ruby version of the template directly.
33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/porthole/template.rb', line 33 def render(context) # Compile our Porthole template into a Ruby string compiled = "def render(ctx) #{compile} end" # Here we rewrite ourself with the interpolated Ruby version of # our Porthole template so subsequent calls are very fast and # can skip the compilation stage. instance_eval(compiled, __FILE__, __LINE__ - 1) # Call the newly rewritten version of #render render(context) end |
#tokens(src = @source) ⇒ Object
Returns an array of tokens for a given template.
54 55 56 |
# File 'lib/porthole/template.rb', line 54 def tokens(src = @source) Parser.new.compile(src) end |