Class: Saper::Items::XML

Inherits:
Saper::Item show all
Defined in:
lib/saper/items/xml.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Saper::Item

#==, [], exists?, inherited, subclasses, try, type, #type

Constructor Details

#initialize(noko) ⇒ XML

Returns a new instance of XML.



26
27
28
29
30
31
# File 'lib/saper/items/xml.rb', line 26

def initialize(noko)
  @noko = noko
  # Force UTF-8 encoding
  # https://github.com/sparklemotion/nokogiri/issues/117
  @noko.document.encoding = 'UTF-8'
end

Class Method Details

.new(item) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/saper/items/xml.rb', line 5

def self.new(item)
  super case item
  when Nokogiri::XML
    item
  when Text
    parse(item.to_s)
  when String
    parse(item)
  else
    raise(InvalidItem, item)
  end
end

.parse(string, uri = nil, charset = nil) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/saper/items/xml.rb', line 18

def self.parse(string, uri = nil, charset = nil)
  begin
    Nokogiri::XML.parse(string, uri, charset)
  rescue
    raise(InvalidItem, string)
  end
end

Instance Method Details

#[](name) ⇒ Object



37
38
39
# File 'lib/saper/items/xml.rb', line 37

def [](name)
  @noko[name]
end

#find(xpath) ⇒ Object



41
42
43
# File 'lib/saper/items/xml.rb', line 41

def find(xpath)
  find_all(xpath).first
end

#find_all(xpath) ⇒ Object



45
46
47
# File 'lib/saper/items/xml.rb', line 45

def find_all(xpath)
  @noko.search(xpath).map { |element| XML.new(element) }
end

#inner_htmlObject



61
62
63
# File 'lib/saper/items/xml.rb', line 61

def inner_html
  @noko.inner_html
end

#inner_textObject



65
66
67
# File 'lib/saper/items/xml.rb', line 65

def inner_text
  @noko.inner_text
end

#nameObject



33
34
35
# File 'lib/saper/items/xml.rb', line 33

def name
  @noko.name
end

#remove(tag) ⇒ Object



57
58
59
# File 'lib/saper/items/xml.rb', line 57

def remove(tag)
  remove_children_preserving_content(tag)
end

#remove_children_preserving_content(xpath) ⇒ Object



53
54
55
# File 'lib/saper/items/xml.rb', line 53

def remove_children_preserving_content(xpath)
  @noko.search(xpath).each { |item| item.replace(item.children) }; self
end

#remove_children_with_content(xpath) ⇒ Object



49
50
51
# File 'lib/saper/items/xml.rb', line 49

def remove_children_with_content(xpath)
  @noko.search(xpath).each { |item| item.remove }; self
end

#to_nativeObject



73
74
75
# File 'lib/saper/items/xml.rb', line 73

def to_native
  inner_html
end

#to_sObject



69
70
71
# File 'lib/saper/items/xml.rb', line 69

def to_s
  inner_html
end