Class: Nokogiri::XML::Element

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext/nokogiri.rb

Constant Summary collapse

BOOLEANIZE_AS_TRUE_RE =
/^(true|yes|oui|ja)$/i.freeze
BOOLEANIZE_AS_FALSE_RE =
/^(false|no|non|nein)$/i.freeze

Instance Method Summary collapse

Instance Method Details

#call(query) ⇒ String, Boolean

Shortcut to query contents array which accepts both String or Symbol queries as well as query postfixes.

Examples:

query optional content for :key

element.(:key)    # same as element.contents[:key]

query mandatory content for :key

element.(:key!)   # fails if the key does not exist

query boolean content for :key

element.(:key?)   # returns true or false

Returns:

Raises:

  • KeyError mandatory or boolean content not found

See Also:

  • and +BOOLEANIZE_AS_FALSE_RE+ define the regular expressions which convert the content to boolean. Furthermore, nil is interpreted as false as well.


42
43
44
45
46
47
48
# File 'lib/core_ext/nokogiri.rb', line 42

def call(query)
  case query
    when /\?$/ then booleanize(contents.fetch(query[...-1].to_sym))
    when /\!$/ then contents.fetch(query[...-1].to_sym)
    else contents[query.to_sym]
  end
end

#contentsHash

Traverse all child elements and build a hash mapping the symbolized child node name to the child content.

Returns:



54
55
56
# File 'lib/core_ext/nokogiri.rb', line 54

def contents
  @contents ||= elements.to_h { [_1.name.to_sym, _1.content] }
end

#find_or_add_child(name, after_css: nil, before_css: nil) ⇒ Nokogiri::XML::Element?

Find this child element or add a new such element if none is found.

The position to add is determined as follows:

  • If after_css is given, its rules are applied in reverse order and the last matching rule defines the predecessor of the added child.

  • If only before_css is given, its rules are applied in order and the first matching rule defines the successor of the added child.

  • If none of the above are given, the child is added at the end.

Parameters:

  • name (Array<String>)

    name of the child element

  • after_css (Array<String>) (defaults to: nil)

    array of CSS rules

  • before_css (Array<String>) (defaults to: nil)

    array of CSS rules

Returns:

  • (Nokogiri::XML::Element, nil)

    element or nil if none found and no position to add a new one could be determined



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

def find_or_add_child(name, after_css: nil, before_css: nil)
  at_css(name) or begin
    case
    when after_css
      at_css(*after_css.reverse).then do |predecessor|
        predecessor&.add_next_sibling("<#{name}/>")
      end&.first
    when before_css
      at_css(*before_css).then do |successor|
        successor&.add_previous_sibling("<#{name}/>")
      end&.first
    else
      add_child("<#{name}/>").first
    end
  end
end