Class: Patm::Pattern::Hash
Instance Method Summary
collapse
#&, #[], build_from, #compile, #opt, #opt?, #rest?
Constructor Details
#initialize(hash, exact) ⇒ Hash
Returns a new instance of Hash.
111
112
113
114
115
|
# File 'lib/patm.rb', line 111
def initialize(hash, exact)
@pat = hash
@exact = exact
@non_opt_count = @pat.values.count{|v| !v.opt? }
end
|
Instance Method Details
#compile_internal(free_index, target_name = "_obj") ⇒ Object
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
# File 'lib/patm.rb', line 129
def compile_internal(free_index, target_name = "_obj")
i = free_index
ctxs = []
src = []
ctxs << [@pat]
i += 1
pat = "_ctx[#{free_index}]"
src << "#{target_name}.is_a?(::Hash)"
src << "#{target_name}.size >= #{@non_opt_count}"
if @exact
src << "#{target_name}.keys.all?{|k| #{pat}.has_key?(k) }"
end
tname = "#{target_name}_elm"
@pat.each do|k, v|
key_src, c, i = Util.compile_value(k, i)
ctxs << c
s, c, i = v.compile_internal(i, tname)
body =
if s
"(#{tname} = #{target_name}[#{key_src}]; #{s})"
else
"true"
end
src <<
if v.opt?
"(!#{target_name}.has_key?(#{key_src}) || #{body})"
else
"(#{target_name}.has_key?(#{key_src}) && #{body})"
end
ctxs << c
end
[
src.join(" &&\n"),
ctxs.flatten(1),
i,
]
end
|
#execute(match, obj) ⇒ Object
116
117
118
119
120
121
122
123
124
125
126
127
|
# File 'lib/patm.rb', line 116
def execute(match, obj)
return false unless obj.is_a?(::Hash)
obj.size >= @non_opt_count &&
(!@exact || obj.keys.all?{|k| @pat.has_key?(k) }) &&
@pat.all? {|k, pat|
if obj.has_key?(k)
pat.execute(match, obj[k])
else
pat.opt?
end
}
end
|
#inspect ⇒ Object
128
|
# File 'lib/patm.rb', line 128
def inspect; @pat.inspect; end
|