class ObjectTemplate
Base class for classes of templates used to match somewhat arbitrary objects.
Constants
- VERSION
Attributes
key_converter[R]
spec[R]
Public Class Methods
new(spec, key_converter = nil)
click to toggle source
The key_converter
is for matching objects that, for example, have had symbol keys serialized to strings. Using a converter that round-trips through the same serializer, symbols in keys will match strings. However, symbols in values will not.
# File lib/object-template.rb 20 def initialize spec, key_converter = nil 21 unless spec.respond_to? :size and spec.respond_to? :each 22 raise ArgumentError, "cannot be used as a template: #{spec.inspect}" 23 end 24 25 @spec = spec 26 @size = spec.size 27 @key_converter = key_converter 28 @matchers = [] 29 30 if spec.respond_to? :to_hash # assume hash-like 31 @shibboleth = :to_hash 32 spec.each do |k, v| 33 if key_converter 34 k = key_converter[k => nil].keys[0] 35 # Note: the [k=>nil].keys[0] is needed instead of just [k] 36 # because the key_converter might not convert values, only keys. 37 # We do not assume that k is a scalar. 38 end 39 fill_matchers k, v 40 end 41 42 else # assume array-like 43 @shibboleth = :to_ary 44 spec.each_with_index do |v, i| 45 fill_matchers i, v unless v.nil? 46 end 47 end 48 end
Public Instance Methods
===(obj)
click to toggle source
True if the template matches the given object. Adapted from rinda/rinda.rb.
# File lib/object-template.rb 70 def === obj 71 return false unless obj.respond_to?(@shibboleth) 72 return false unless @size == obj.size 73 @matchers.each do |k, v| 74 begin 75 it = obj.fetch(k) 76 rescue 77 return false 78 end 79 next if v.nil? 80 next if v == it 81 next if v === it 82 return false 83 end 84 return true 85 end
inspect()
click to toggle source
# File lib/object-template.rb 87 def inspect 88 "<#{self.class}: #{@spec}>" 89 end
optimize!()
click to toggle source
Reorders the list of matchers so that easy ones come first. For example: nil, then single values (==), then patterns (===). Returns self.
# File lib/object-template.rb 53 def optimize! 54 @matchers.sort_by! do |k, v| 55 case v 56 when nil; 0 57 when Range; 2 58 when Module; 3 59 when Regexp; 4 60 when MemberMatchingSet; 4 61 when Proc; 5 62 else 1 # assume it is a value 63 end 64 end 65 self 66 end