Class: Nokogiri::HTML::DocumentFragment

Inherits:
XML::DocumentFragment show all
Defined in:
lib/nokogiri/html/document_fragment.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document, tags = nil, ctx = nil) ⇒ DocumentFragment

Returns a new instance of DocumentFragment.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/nokogiri/html/document_fragment.rb', line 26

def initialize document, tags = nil, ctx = nil
  return self unless tags

  if ctx
    preexisting_errors = document.errors.dup
    node_set = ctx.parse("<div>#{tags}</div>")
    node_set.first.children.each { |child| child.parent = self } unless node_set.empty?
    self.errors = document.errors - preexisting_errors
  else
    # This is a horrible hack, but I don't care
    if tags.strip =~ /^<body/i
      path = "/html/body"
    else
      path = "/html/body/node()"
    end

    temp_doc = HTML::Document.parse "<html><body>#{tags}", nil, document.encoding
    temp_doc.xpath(path).each { |child| child.parent = self }
    self.errors = temp_doc.errors
  end
  children
end

Class Method Details

.parse(tags, encoding = nil) ⇒ Object

Create a Nokogiri::XML::DocumentFragment from tags, using encoding



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/nokogiri/html/document_fragment.rb', line 7

def self.parse tags, encoding = nil
  doc = HTML::Document.new

  encoding ||= if tags.respond_to?(:encoding)
                 encoding = tags.encoding
                 if encoding == ::Encoding::ASCII_8BIT
                   'UTF-8'
                 else
                   encoding.name
                 end
               else
                 'UTF-8'
               end

  doc.encoding = encoding

  new(doc, tags)
end