Method: Nokogiri::HTML4::DocumentFragment#initialize

Defined in:
lib/nokogiri/html4/document_fragment.rb

#initialize(document, input = nil, context_ = nil, options_ = XML::ParseOptions::DEFAULT_HTML, context: context_, options: options_) {|options| ... } ⇒ DocumentFragment

:call-seq:

new(document) { |options| ... } → HTML4::DocumentFragment
new(document, input) { |options| ... } → HTML4::DocumentFragment
new(document, input, context:, options:) { |options| ... } → HTML4::DocumentFragment

Parse HTML4 fragment input from a String, and return a new HTML4::DocumentFragment.

💡 It’s recommended to use either HTML4::DocumentFragment.parse or XML::Node#parse rather than call this method directly.

Required Parameters
  • document (HTML4::Document) The parent document to associate the returned fragment with.

Optional Parameters
  • input (String) The content to be parsed.

Optional Keyword Arguments
  • context: (Nokogiri::XML::Node) The context node for the subtree created. See below for more information.

  • options: (Nokogiri::XML::ParseOptions) Configuration object that determines some behaviors during parsing. See ParseOptions for more information. The default value is ParseOptions::DEFAULT_HTML.

Yields

If a block is given, a Nokogiri::XML::ParseOptions object is yielded to the block which can be configured before parsing. See ParseOptions for more information.

Returns

HTML4::DocumentFragment

Context Node

If a context node is specified using context:, then the fragment will be created by calling XML::Node#parse on that node, so the parser will behave as if that Node is the parent of the fragment subtree.

Yields:

  • (options)


134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/nokogiri/html4/document_fragment.rb', line 134

def initialize(
  document, input = nil,
  context_ = nil, options_ = XML::ParseOptions::DEFAULT_HTML,
  context: context_, options: options_
) # rubocop:disable Lint/MissingSuper
  return self unless input

  options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
  @parse_options = options
  yield options if block_given?

  if context
    preexisting_errors = document.errors.dup
    node_set = context.parse("<div>#{input}</div>", options)
    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
    path = if /^\s*?<body/i.match?(input)
      "/html/body"
    else
      "/html/body/node()"
    end

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