Class: Template::Test::Context
- Inherits:
-
Object
- Object
- Template::Test::Context
- Defined in:
- lib/template-test.rb
Overview
Class that holds the context for a template Variables used by the template can be added to the context using the set method.
Instance Attribute Summary collapse
-
#html ⇒ String
The rendered template.
-
#nodes ⇒ Object
Returns the value of attribute nodes.
-
#template_path ⇒ Object
writeonly
Sets the attribute template_path.
Instance Method Summary collapse
-
#document(reload = false) ⇒ Nokogiri::HTML
The document that wraps the rendered template.
-
#render ⇒ String
Renders the template.
-
#set(symbol, value) ⇒ Object
(also: #assign)
Assigns an instance variable which is available when the template is rendered.
-
#xpath(xpath, &block) ⇒ Object
Searches the rendered HTML document for the given XPATH query.
Instance Attribute Details
#html ⇒ String
Returns the rendered template.
24 25 26 |
# File 'lib/template-test.rb', line 24 def html() @html ||= render(); end |
#nodes ⇒ Object
Returns the value of attribute nodes.
11 12 13 |
# File 'lib/template-test.rb', line 11 def nodes @nodes end |
#template_path=(value) ⇒ Object (writeonly)
Sets the attribute template_path
12 13 14 |
# File 'lib/template-test.rb', line 12 def template_path=(value) @template_path = value end |
Instance Method Details
#document(reload = false) ⇒ Nokogiri::HTML
Returns the document that wraps the rendered template.
16 17 18 19 20 21 |
# File 'lib/template-test.rb', line 16 def document(reload = false) if reload @document = nil end @document ||= Nokogiri::HTML(html()) end |
#render ⇒ String
Renders the template. All variables defined by @see #set are available in the template. They can be accessed as instance variables or by using the attribute accessor.
56 57 58 59 60 61 62 63 64 65 |
# File 'lib/template-test.rb', line 56 def render case @template_path when /\.erb$/ render_erb(@template_path) when /\.haml$/ render_haml(@template_path) else raise StandardError, "Unsupported template #{@template_path}" end end |
#set(symbol, value) ⇒ Object Also known as: assign
Assigns an instance variable which is available when the template is rendered.
44 45 46 47 48 49 50 |
# File 'lib/template-test.rb', line 44 def set(symbol, value) sym = "@#{symbol.to_s}".to_sym instance_variable_set(sym, value) self.send(:define_singleton_method, symbol) do instance_variable_get(sym) end end |
#xpath(xpath, &block) ⇒ Object
Searches the rendered HTML document for the given XPATH query. In the given block the result of the xpath query is available through the ‘nodes’ instance variable.
34 35 36 37 38 |
# File 'lib/template-test.rb', line 34 def xpath(xpath, &block) @xpath = xpath @nodes = document().xpath(@xpath) self.instance_eval(&block) end |