Class: PostRunner::HTMLBuilder
- Inherits:
-
Object
- Object
- PostRunner::HTMLBuilder
- 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
-
#initialize ⇒ HTMLBuilder
constructor
Create a new HTMLBuilder object.
-
#method_missing(method_name, *args) ⇒ Object
Any call to an undefined method will create a HTML node of the same name.
-
#respond_to?(method) ⇒ Boolean
Only needed to comply with style guides.
-
#to_html ⇒ Object
Dump the HTML document as HTML formatted String.
Constructor Details
#initialize ⇒ HTMLBuilder
Create a new HTMLBuilder object.
22 23 24 25 26 27 28 |
# File 'lib/postrunner/HTMLBuilder.rb', line 22 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.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/postrunner/HTMLBuilder.rb', line 32 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.
57 58 59 |
# File 'lib/postrunner/HTMLBuilder.rb', line 57 def respond_to?(method) true end |
#to_html ⇒ Object
Dump the HTML document as HTML formatted String.
62 63 64 |
# File 'lib/postrunner/HTMLBuilder.rb', line 62 def to_html @doc.to_html end |