Class: PostRunner::HTMLBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/postrunner/HTMLBuilder.rb

Overview

Nokogiri is great, but I don’t like the HTMLBuilder interface. This class is a wrapper around Nokogiri that provides a more Ruby-like interface.

Instance Method Summary collapse

Constructor Details

#initializeHTMLBuilder

Create a new HTMLBuilder object.



10
11
12
13
14
15
16
# File 'lib/postrunner/HTMLBuilder.rb', line 10

def initialize
  # This is the Nokogiri Document that will store all the data.
  @doc = Nokogiri::HTML::Document.new
  # We only need to keep a stack of the currently edited nodes so we know
  # where we are in the node tree.
  @node_stack = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object

Any call to an undefined method will create a HTML node of the same name.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/postrunner/HTMLBuilder.rb', line 20

def method_missing(method_name, *args)
  node = Nokogiri::XML::Node.new(method_name.to_s, @doc)
  if (parent = @node_stack.last)
    parent.add_child(node)
  else
    @doc.add_child(node)
  end
  @node_stack.push(node)

  args.each do |arg|
    if arg.is_a?(String)
      node.add_child(Nokogiri::XML::Text.new(arg, @doc))
    elsif arg.is_a?(Hash)
      # Hash arguments are attribute sets for the node. We just pass them
      # directly to the node.
      arg.each { |k, v| node[k] = v }
    end
  end

  yield if block_given?
  @node_stack.pop
end

Instance Method Details

#respond_to?(method) ⇒ Boolean

Only needed to comply with style guides. This all calls to unknown method will be handled properly. So, we always return true.

Returns:

  • (Boolean)


45
46
47
# File 'lib/postrunner/HTMLBuilder.rb', line 45

def respond_to?(method)
  true
end

#to_htmlObject

Dump the HTML document as HTML formatted String.



50
51
52
# File 'lib/postrunner/HTMLBuilder.rb', line 50

def to_html
  @doc.to_html
end