Class: Yoda::IdMask
- Inherits:
-
Object
- Object
- Yoda::IdMask
- Defined in:
- lib/yoda/id_mask.rb
Instance Attribute Summary collapse
- #pattern ⇒ Hash<Symbol>? readonly
Class Method Summary collapse
Instance Method Summary collapse
- #any? ⇒ Boolean
- #cover?(id) ⇒ Boolean
- #covering_ids ⇒ Set<Symbol>?
-
#initialize(pattern) ⇒ IdMask
constructor
A new instance of IdMask.
- #intersection(another) ⇒ IdMask (also: #&)
- #nesting_mask(id) ⇒ IdMask
- #to_pattern ⇒ Hash?
Constructor Details
#initialize(pattern) ⇒ IdMask
Returns a new instance of IdMask.
23 24 25 26 |
# File 'lib/yoda/id_mask.rb', line 23 def initialize(pattern) fail TypeError, "pattern must be a Hash or nil" unless pattern.is_a?(Hash) || pattern.nil? @pattern = pattern end |
Instance Attribute Details
#pattern ⇒ Hash<Symbol>? (readonly)
6 7 8 |
# File 'lib/yoda/id_mask.rb', line 6 def pattern @pattern end |
Class Method Details
.build(pattern) ⇒ IdMask
10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/yoda/id_mask.rb', line 10 def self.build(pattern) if pattern.is_a?(IdMask) pattern elsif pattern.nil? new(pattern) elsif pattern.is_a?(Hash) new(pattern.map { |k, v| [k.to_sym, v] }.to_h) else new(pattern.to_a.to_h { |id| [id.to_sym, nil] }) end end |
Instance Method Details
#any? ⇒ Boolean
54 55 56 |
# File 'lib/yoda/id_mask.rb', line 54 def any? pattern.nil? end |
#cover?(id) ⇒ Boolean
30 31 32 33 |
# File 'lib/yoda/id_mask.rb', line 30 def cover?(id) return true if any? pattern.has_key?(id.to_sym) end |
#covering_ids ⇒ Set<Symbol>?
59 60 61 62 63 64 65 66 67 |
# File 'lib/yoda/id_mask.rb', line 59 def covering_ids @covering_ids ||= begin if any? nil else Set.new(pattern.keys) end end end |
#intersection(another) ⇒ IdMask Also known as: &
37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/yoda/id_mask.rb', line 37 def intersection(another) another_mask = IdMask.build(another) return another_mask if any? return self if another_mask.any? ids_intersection = covering_ids & another_mask.covering_ids intersection_pattern = ids_intersection.map do |id| [id, nesting_mask(id) & another_mask.nesting_mask(id)] end.to_h IdMask.build(intersection_pattern) end |
#nesting_mask(id) ⇒ IdMask
71 72 73 74 75 76 77 |
# File 'lib/yoda/id_mask.rb', line 71 def nesting_mask(id) if pattern.is_a?(Hash) IdMask.build(pattern[id.to_sym]) else IdMask.build(nil) end end |
#to_pattern ⇒ Hash?
80 81 82 |
# File 'lib/yoda/id_mask.rb', line 80 def to_pattern pattern&.map { |k, v| [k, v&.to_pattern] }&.to_h end |