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

#initialize(title) ⇒ HTMLBuilder

Create a new HTMLBuilder object.



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

def initialize(title)
  # 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 = []
  @tags = []

  @html = create_node('html') {
    @head = create_node('head') {
      create_node('meta', { 'http-equiv' => 'Content-Type',
                  'content' => 'text/html; charset=utf-8' })
      create_node('title', title)
    }
    @body = create_node('body')
  }
  @node_stack << @html
  @node_stack << @body
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object

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



76
77
78
# File 'lib/postrunner/HTMLBuilder.rb', line 76

def method_missing(method_name, *args, &block)
  create_node(method_name.to_s, *args, &block)
end

Instance Method Details

#body(*args) ⇒ Object

Append nodes provided in block to body section of HTML document.



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/postrunner/HTMLBuilder.rb', line 52

def body(*args)
  @node_stack.push(@body)
  args.each do |arg|
    if arg.is_a?(Hash)
      arg.each { |k, v| @body[k] = v }
    end
  end
  yield if block_given?
  unless @node_stack.pop == @body
    raise ArgumentError, "node_stack corrupted in body"
  end
end

#headObject

Append nodes provided in block to head section of HTML document.



43
44
45
46
47
48
49
# File 'lib/postrunner/HTMLBuilder.rb', line 43

def head
  @node_stack.push(@head)
  yield if block_given?
  unless @node_stack.pop == @head
    raise ArgumentError, "node_stack corrupted in head"
  end
end

#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)


82
83
84
# File 'lib/postrunner/HTMLBuilder.rb', line 82

def respond_to?(method)
  true
end

#to_htmlObject

Dump the HTML document as HTML formatted String.



87
88
89
# File 'lib/postrunner/HTMLBuilder.rb', line 87

def to_html
  @doc.to_html
end

#unique(tag) ⇒ Object

Only execute the passed block if the provided tag has not been added yet.



67
68
69
70
71
72
# File 'lib/postrunner/HTMLBuilder.rb', line 67

def unique(tag)
  unless @tags.include?(tag)
    @tags << tag
    yield if block_given?
  end
end