forked from microformats/microformats-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollection.rb
102 lines (82 loc) · 2.08 KB
/
collection.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
module Microformats
# stub to get around the tests for now
class Collection
def initialize(hash)
@hash = hash
end
def to_h
@hash
end
def to_hash
@hash
end
def to_json
to_hash.to_json
end
def to_s
@hash.to_s
end
def [](key)
@hash[key]
end
def items
@hash['items'].map do |item|
ParserResult.new(item)
end
end
def rels
@hash['rels']
end
def rel_urls
@hash['rel-urls']
end
def respond_to?(sym, include_private = false)
item?(sym) || super(sym, include_private)
end
def method_missing(sym, *args, &block)
name = sym.to_s
name_dash = name.tr('_', '-') if name.include?('_')
unless @hash['items'].nil?
result_hash = @hash['items'].select do |x|
x['type'].include?('h-' + name)
end
if result_hash.empty? && !name_dash.nil?
result_hash = @hash['items'].select do |x|
x['type'].include?('h-' + name_dash)
end
end
end
super(sym, *args, &block) if result_hash.empty?
if result_hash.is_a?(Array)
if args[0].nil?
result_hash = result_hash[0] # will return nil for an empty array
elsif args[0] == :all
return result_hash.map do |x|
ParserResult.new(x)
end
elsif args[0].to_i < result_hash.count
result_hash = result_hash[args[0].to_i]
else
result_hash = result_hash[0] # will return nil for an empty array
end
end
ParserResult.new(result_hash)
end
private
def item?(name)
name = name.to_s
name_dash = name.tr('_', '-') if name.include?('_')
unless @hash['items'].nil?
result_hash = @hash['items'].select do |x|
x['type'].include?('h-' + name)
end
if result_hash.empty? && !name_dash.nil?
result_hash = @hash['items'].select do |x|
x['type'].include?('h-' + name_dash)
end
end
end
!result_hash.empty?
end
end
end