Class: RexleXPath

Inherits:
Object
  • Object
show all
Defined in:
lib/rexle-xpath.rb

Instance Method Summary collapse

Constructor Details

#initialize(node = nil, debug: false) ⇒ RexleXPath

Returns a new instance of RexleXPath.



23
24
25
26
27
28
# File 'lib/rexle-xpath.rb', line 23

def initialize(node=nil, debug: false)

  @node = node
  @debug = debug
  
end

Instance Method Details

#parse(s) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rexle-xpath.rb', line 30

def parse(s)

  # it's an xpath function only
  if /^(?<name>\w+)\(\)$/ =~ s
    
    @node.method((name).to_sym).call
    
  # it's an element only
  elsif /^(?<name>\w+)$/ =~ s
    
    select(@node, [name])
    
  else

    xpath_instructions = RexleXPathParser.new(s).to_a
    #puts 'xpath_instructions: ' + xpath_instructions.inspect
    
    query xpath_instructions, @node
  end
end

#query(xpath_instructions = [], node = @node) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rexle-xpath.rb', line 52

def query(xpath_instructions=[], node=@node)

  debug :query, node: node, xpath_instructions: xpath_instructions

  row = xpath_instructions.shift
  method_name, *args = row

  return query row + xpath_instructions, node if row.first.is_a? Array    

  result = if method_name == :predicate then

    result2 = method(method_name.to_sym).call node, args,[]
    
    if result2 and xpath_instructions.any? then
      query xpath_instructions, node
    else
      result2
    end
    
  else

    method(method_name.to_sym).call node, args, xpath_instructions
  end

  result.is_a?(Array) ? result.flatten : result

end