Class: Leptris::XML::XPath

Inherits:
Object
  • Object
show all
Defined in:
lib/leptris/xml/xpath.rb

Overview

Compiled XPath expression: parse once, evaluate many times against any document (libleptris v1.6.0). The C handle is released by GC.

expr = Leptris::XML::XPath.compile("//item[@qty > 3]")
expr.eval(doc_a).length
expr.eval(doc_b, "p" => "urn:p").length

Defined Under Namespace

Classes: CompiledHandle

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression, handle) ⇒ XPath

Returns a new instance of XPath.



30
31
32
33
# File 'lib/leptris/xml/xpath.rb', line 30

def initialize(expression, handle)
  @expression = expression
  @handle = handle
end

Instance Attribute Details

#expressionObject (readonly)

Returns the value of attribute expression.



19
20
21
# File 'lib/leptris/xml/xpath.rb', line 19

def expression
  @expression
end

Class Method Details

.compile(expression) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/leptris/xml/xpath.rb', line 21

def self.compile(expression)
  raw = Leptris::XML::FFI.leptris_xpath_compile(expression.to_s)
  if raw.null?
    raise Leptris::XML::XPathError,
      "invalid expression: #{Leptris::XML::FFI.leptris_last_error}"
  end
  new(expression.to_s, CompiledHandle.new(raw))
end

Instance Method Details

#eval(doc_or_element, ns = nil) ⇒ Object

Evaluates against doc_or_element. An optional trailing hash of namespace bindings ("prefix" => uri) routes the evaluation through the namespace-bound path, matching Searchable#xpath semantics.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/leptris/xml/xpath.rb', line 38

def eval(doc_or_element, ns = nil)
  context = resolve_context(doc_or_element)
  document = context.document
  result_ptr =
    if ns && !ns.empty?
      Leptris::XML::FFI.with_ns_set(ns) do |set|
        Leptris::XML::FFI.leptris_xpath_compiled_eval_ns(
          @handle, document.c_ptr, context_ptr(context), set)
      end
    else
      Leptris::XML::FFI.leptris_xpath_compiled_eval(
        @handle, document.c_ptr, context_ptr(context))
    end
  if result_ptr.null?
    raise Leptris::XML::XPathError,
      Leptris::XML::FFI.leptris_last_error.to_s
  end
  Leptris::XML::Searchable.wrap_xpath_result(document, result_ptr)
end