Module: KindDom::Kindness

Defined in:
lib/kind_dom.rb

Instance Method Summary collapse

Instance Method Details

#collection_of(xpath, default = nil) ⇒ Object

Retrieve a collection (Array) of DOM nodes selected by the XPath.

Each node is extended with Kindness to support #content_for, #collection_of & #first_of.

When a block is provided, it will be used to transform the found collection (or default) before returning.



81
82
83
84
85
86
87
88
89
90
91
# File 'lib/kind_dom.rb', line 81

def collection_of(xpath, default=nil)
  c = find(xpath).collect {|n| n.extend Kindness }
rescue NoMethodError
ensure
  c = c.blank?||c.size<1 ? default : c
  if block_given? and !c.nil?
    return yield(c)
  else
    return c
  end
end

#content_for(xpath, default = nil) ⇒ Object

Retrieve the contents of the first node or attribute selected by the XPath.

Optional second argument is the default value to return if the DOM find fails.

When a block is provided, it will be used to transform the found content (or default) before returning.

The block should except one argument: the content to tranform.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/kind_dom.rb', line 51

def content_for(xpath, default=nil)
  node = case self.class.to_s
  when 'XML::Document' then
    root.find_first(xpath)
  else # 'XML::Node'
    find_first(xpath)
  end
  content = case node.class.to_s
  when 'XML::Attr' then
    node.value
  else
    node.content
  end
rescue NoMethodError
ensure
  content = content.blank? ? default : content
  if block_given? and !content.blank?
    return yield(content)
  else
    return content
  end
end

#first_of(xpath, default = nil) ⇒ Object

Retrieve the first DOM node selected by the XPath.

The node is extended with Kindness to support #content_for, #collection_of & #first_of.

When a block is provided, it will be used to transform the found node (or default) before returning.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/kind_dom.rb', line 100

def first_of(xpath, default=nil)
  n = case self.class.to_s
  when 'XML::Document' then
    root.find_first(xpath)
  else # 'XML::Node'
    find_first(xpath)
  end
  n.extend Kindness
rescue NoMethodError
ensure
  n = n.blank? ? default : n
  if block_given? and !n.blank?
    return yield(n)
  else
    return n
  end
end