class Patm::Pattern::Hash

Public Class Methods

new(hash, exact) click to toggle source
# File lib/patm.rb, line 128
def initialize(hash, exact)
  @pat = hash
  @exact = exact
  @non_opt_count = @pat.values.count{|v| !v.opt? }
end

Public Instance Methods

compile_internal(free_index, target_name = "_obj") click to toggle source
# 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) click to toggle source
# 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
inspect() click to toggle source
# File lib/patm.rb, line 145
def inspect; @pat.inspect; end