Class: Template::Test::Context

Inherits:
Object
  • Object
show all
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.

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#htmlString

Returns the rendered template.

Returns:

  • (String)

    the rendered template



24
25
26
# File 'lib/template-test.rb', line 24

def html()
  @html ||= render();
end

#nodesObject

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

Parameters:

  • value

    the value to set the attribute template_path to.



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.

Parameters:

  • reload (Boolean) (defaults to: false)

    true if the document should be parsed again

Returns:

  • (Nokogiri::HTML)

    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

#renderString

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.

Returns:

  • (String)

    the rendered template



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.

Examples:

see erb_spec.

Parameters:

  • symbol (Symbol)

    the name of the instance variable

  • value (Object)

    the value of the instance variable



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.

Examples:

see erb_spec.

Parameters:

  • xpath (String)

    an XPATH search expression

  • block (Proc)

    the testing code



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