Module: Peppercorn::XML::Node

Included in:
Nokogiri::XML::Node
Defined in:
lib/peppercorn/xml/node.rb

Overview

Extensions to Nokogiri::XML::Node

Instance Method Summary collapse

Instance Method Details

#appendable_nodeObject

Returns the last appendable child node (the last block-level element) return [Nokogiri::XML::Node] since 0.0.2



56
57
58
59
60
61
62
63
64
65
# File 'lib/peppercorn/xml/node.rb', line 56

def appendable_node
  current = children.last
  loop do
    if current.text? or current.description.inline?
      return current.parent
    end
    current = current.children.last
  end
  return current
end

#last_text_nodeNokogiri::XML::Node

Returns the last child node that is a text node

Returns:

Since:

  • 0.0.1



70
71
72
73
74
75
76
77
78
79
# File 'lib/peppercorn/xml/node.rb', line 70

def last_text_node
  return self if text? and !content.empty?

  children.reverse.each do |child|
    ltn = child.last_text_node
    return ltn unless ltn.nil?
  end

  return nil
end

#truncate(length, opts = {}) ⇒ String

Truncate a string of html to “length” words

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

Returns:

  • (String)

    the truncated html

Since:

  • 0.0.1



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/peppercorn/xml/node.rb', line 11

def truncate(length, opts={})
  opts = Peppercorn::DEFAULT_TRUNCATION_OPTIONS.merge(opts)
    
  doc = self
  target = nil
  count = 0
  overran = false
    
  if doc.text?
    result = content.peppercorn_truncate(length, opts.merge(Peppercorn::TRUNCATE_CHILD_OPTS))
    target = result[:text]
    count = result[:count]
    overran = result[:overran]
  else
    target = doc.clone
    target.children.remove
    doc.children.each do |child|
      result = child.truncate(length-count, opts.merge(Peppercorn::TRUNCATE_CHILD_OPTS))
      count += result[:count]
      overran = result[:overran]
      target << result[:text]
      break if overran
    end
  end
  
  return nil if target.nil?
  
  
  if opts[:strip]
    last_text_node = target.last_text_node
    last_text_node.content = last_text_node.content.strip_end if last_text_node
  end
  
  if !opts[:tail].to_s.empty? and overran
    target.appendable_node << Nokogiri::HTML::DocumentFragment.parse(opts[:tail])
  end
  
  target = target.inner_html unless opts[:return_node]
  return opts[:return_hash] ? {:text => target, :count => [count, length].min, :overran => overran} : target
    
end