Module: Oga::XPath::Conversion

Defined in:
lib/oga/xpath/conversion.rb

Overview

Module for converting XPath objects such as NodeSets.

Class Method Summary collapse

Class Method Details

.boolean?(value) ⇒ TrueClass|FalseClass

Returns:

  • (TrueClass|FalseClass)


91
92
93
# File 'lib/oga/xpath/conversion.rb', line 91

def self.boolean?(value)
  value == true || value == false
end

.first_node_text(set) ⇒ String

Parameters:

Returns:

  • (String)


97
98
99
# File 'lib/oga/xpath/conversion.rb', line 97

def self.first_node_text(set)
  set[0].respond_to?(:text) ? set[0].text : ''
end

.to_boolean(value) ⇒ TrueClass|FalseClass

Returns:

  • (TrueClass|FalseClass)


74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/oga/xpath/conversion.rb', line 74

def self.to_boolean(value)
  bool = false

  if value.is_a?(Float)
    bool = !value.nan? && !value.zero?
  elsif value.is_a?(Integer)
    bool = !value.zero?
  elsif value.respond_to?(:empty?)
    bool = !value.empty?
  elsif value
    bool = true
  end

  bool
end

.to_compatible_types(left, right) ⇒ Array

Converts both arguments to a type that can be compared using ==.

Returns:

  • (Array)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/oga/xpath/conversion.rb', line 10

def self.to_compatible_types(left, right)
  if left.is_a?(XML::NodeSet) or left.respond_to?(:text)
    left = to_string(left)
  end

  if right.is_a?(XML::NodeSet) or right.respond_to?(:text)
    right = to_string(right)
  end

  if left.is_a?(Numeric) and !right.is_a?(Numeric)
    right = to_float(right)
  end

  if left.is_a?(String) and !right.is_a?(String)
    right = to_string(right)
  end

  if boolean?(left) and !boolean?(right)
    right = to_boolean(right)
  end

  [left, right]
end

.to_float(value) ⇒ Float

Returns:

  • (Float)


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/oga/xpath/conversion.rb', line 55

def self.to_float(value)
  if value.is_a?(XML::NodeSet)
    value = first_node_text(value)
  end

  if value.respond_to?(:text)
    value = value.text
  end

  if value == true
    1.0
  elsif value == false
    0.0
  else
    Float(value) rescue Float::NAN
  end
end

.to_string(value) ⇒ String

Returns:

  • (String)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/oga/xpath/conversion.rb', line 35

def self.to_string(value)
  # If we have a number that has a zero decimal (e.g. 10.0) we want to
  # get rid of that decimal. For this we'll first convert the number to
  # an integer.
  if value.is_a?(Float) and value.modulo(1).zero?
    value = value.to_i
  end

  if value.is_a?(XML::NodeSet)
    value = first_node_text(value)
  end

  if value.respond_to?(:text)
    value = value.text
  end

  value.to_s
end