Module: Nom::XML::Decorators::NodeSet

Defined in:
lib/nom/xml/decorators/nodeset.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object

Add a #method_missing handler to NodeSets. If all of the elements in the Nodeset respond to a method (e.g. if it is a term accessor), call that method on all the elements in the node


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/nom/xml/decorators/nodeset.rb', line 31

def method_missing sym, *args, &block
  if self.all? { |node| node.respond_to? sym }
    result = self.collect { |node| node.send(sym, *args, &block) }.flatten
    if result.empty? || result.any? { |x| x.is_a? Nokogiri::XML::Node }
      self.class.new(self.document, result) rescue result
    else
      result
    end
  else
    begin
      self.document.template_registry.send(sym, self, *args, &block)
    rescue NameError
      super
    end
  end
end

Instance Method Details

#respond_to_missing?(sym, priv = false) ⇒ Boolean

ruby 2.0 sends two arguments to respond_to?

Returns:

  • (Boolean)

49
50
51
52
53
54
55
# File 'lib/nom/xml/decorators/nodeset.rb', line 49

def respond_to_missing? sym, priv = false
    if self.all? { |node| node.respond_to? sym }
      true
    else
      super
    end
end

#values_for_term(term) ⇒ Object


3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/nom/xml/decorators/nodeset.rb', line 3

def values_for_term term
    result = self
    result = result.select &(term.options[:if]) if term.options[:if].is_a? Proc
    result = result.reject &(term.options[:unless]) if term.options[:unless].is_a? Proc

    m = term.options[:accessor]
    return_value = case
      when m.nil?
        result
      when m.is_a?(Symbol)
         result.collect { |r| r.send(m) }.compact
      when m.is_a?(Proc)
        result.collect { |r| m.call(r) }.compact
      else
        raise "Unknown accessor class: #{m.class}"
      end

    if return_value and (term.options[:single] or (result.length == 1 and result.first.is_a? Nokogiri::XML::Attr))
      return return_value.first
    end

    return return_value
end