Class: Saper::Items::JSON
Class Method Summary
collapse
Instance Method Summary
collapse
Methods inherited from Saper::Item
#==, [], exists?, inherited, subclasses, try, type, #type
Constructor Details
#initialize(hash) ⇒ JSON
Returns a new instance of JSON.
24
25
26
|
# File 'lib/saper/items/json.rb', line 24
def initialize(hash)
@hash = hash
end
|
Class Method Details
.new(item) ⇒ Object
5
6
7
8
9
10
11
12
13
14
|
# File 'lib/saper/items/json.rb', line 5
def self.new(item)
super case item
when Text
parse(item.to_s)
when String
parse(item)
else
raise(InvalidItem, item)
end
end
|
.parse(string) ⇒ Object
16
17
18
19
20
21
22
|
# File 'lib/saper/items/json.rb', line 16
def self.parse(string)
begin
::JSON.parse(string)
rescue
raise(InvalidItem, string)
end
end
|
Instance Method Details
#[](name) ⇒ Object
28
29
30
31
32
33
34
35
36
37
38
|
# File 'lib/saper/items/json.rb', line 28
def [](name)
value = @hash[name.to_s]
case value
when Hash
self.class.new(value)
when Array
self.class.new(value)
else
value
end
end
|
#find(xpath) ⇒ Object
40
41
42
|
# File 'lib/saper/items/json.rb', line 40
def find(xpath)
find_all(xpath).first
end
|
#find_all(xpath) ⇒ Object
44
45
46
47
48
|
# File 'lib/saper/items/json.rb', line 44
def find_all(xpath)
JSONSearch.find(@hash, xpath).map do |item|
sanitize(item)
end
end
|
#sanitize(item) ⇒ Object
50
51
52
53
54
55
56
57
58
59
|
# File 'lib/saper/items/json.rb', line 50
def sanitize(item)
case item
when Hash
self.class.new(item)
when Array
item.map { |i| sanitize(i) }
else
item
end
end
|
#to_native ⇒ Object
61
62
63
|
# File 'lib/saper/items/json.rb', line 61
def to_native
@hash
end
|