class REHTML::REXMLBuilder

Constants

CDATA_TAGS
EMPTY_TAGS

Attributes

doc[R]

Public Instance Methods

append(node) click to toggle source

append node to document

# File lib/rehtml/builder.rb, line 19
def append(node)
  if node.is_a?(EndTag)
    return if empty_tag?(node.name)
    po = @pos
    while po.parent and po.name != node.name
      po = po.parent
    end
    if po.name == node.name
      @pos = po.parent
    end
  else
    rexml = to_rexml(node)

    # if node is second root element, add root element wrap html tag
    if rexml.is_a?(REXML::Element) and @pos == @doc and @doc.root
      if @doc.root.name != 'html'
        html = REXML::Element.new
        html.name = "html"
        i = @doc.root.index_in_parent-1
        while pos = @doc.delete_at(i)
          @doc.delete_element(pos) if pos.is_a?(REXML::Element)
          html << pos
        end
        @doc << html
        @pos = html
      end
      @pos = @doc.root
    end
    @pos << rexml
    if rexml.is_a?(REXML::Element) and !empty_tag?(node.name) and !node.empty?
      @pos = rexml
    end
  end
end
parse(tokenizer) click to toggle source

build document use tokenizer

# File lib/rehtml/builder.rb, line 10
def parse(tokenizer)
  @doc = REXML::Document.new
  @pos = @doc
  while node=tokenizer.next
    append(node)
  end
end

Private Instance Methods

cdata_tag?(tagname) click to toggle source
# File lib/rehtml/builder.rb, line 92
def cdata_tag?(tagname)
  CDATA_TAGS.include?(tagname)
end
empty_tag?(tagname) click to toggle source
# File lib/rehtml/builder.rb, line 88
def empty_tag?(tagname)
  EMPTY_TAGS.include?(tagname)
end
to_rexml(node) click to toggle source
# File lib/rehtml/builder.rb, line 56
def to_rexml(node)
  case node
  when Text
    REXML::Text.new(node.value, true)
  when CData
    REXML::CData.new(node.value)
  when Instruction
    if node.is_xml_decl? and ( @doc.xml_decl.nil? or !@doc.xml_decl.writethis )
      begin
        return REXML::Document.new("<?xml #{node.content}?>").xml_decl
      rescue REXML::ParseException
      end
    end
    REXML::Instruction.new(node.target,node.content)
  when DocType
    REXML::Comment.new(node.raw)
  when Comment
    REXML::Comment.new(node.string)
  when Tag
    if cdata_tag?(@pos.name)
      REXML::Text.new(node.raw, true)
    else
      xml = REXML::Element.new
      xml.name = node.name
      xml.add_attributes(node.attributes)
      xml
    end
  else
    raise "unknown node type #{node}"
  end
end