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, #compile, #opt, #opt?, #rest?

Constructor Details

#initialize(hash, exact) ⇒ Hash

Returns a new instance of Hash.



120
121
122
123
124
# File 'lib/patm.rb', line 120

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



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
168
169
170
171
172
173
174
175
176
# File 'lib/patm.rb', line 138

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



125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/patm.rb', line 125

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



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

def inspect; @pat.inspect; end