Class: Patm::Pattern::Hash

Inherits:
Patm::Pattern show all
Defined in:
lib/patm.rb

Instance Method Summary collapse

Methods inherited from Patm::Pattern

#&, #[], build_from, build_from_array, build_from_hash, #compile, #opt, #opt?, #rest?

Constructor Details

#initialize(hash, exact) ⇒ Hash

Returns a new instance of Hash.



128
129
130
131
132
# File 'lib/patm.rb', line 128

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



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/patm.rb', line 146

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



133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/patm.rb', line 133

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

#inspectObject



145
# File 'lib/patm.rb', line 145

def inspect; @pat.inspect; end