Class: Yoda::IdMask

Inherits:
Object
  • Object
show all
Defined in:
lib/yoda/id_mask.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ IdMask

Returns a new instance of IdMask.

Parameters:

  • pattern (Hash<Symbol>, nil)


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

#patternHash<Symbol>? (readonly)

Returns:

  • (Hash<Symbol>, nil)


6
7
8
# File 'lib/yoda/id_mask.rb', line 6

def pattern
  @pattern
end

Class Method Details

.build(pattern) ⇒ IdMask

Parameters:

  • pattern (IdMask, Set<Symbol>, Array<Symbol>, Hash<Symbol>, nil)

Returns:



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

Returns:

  • (Boolean)


54
55
56
# File 'lib/yoda/id_mask.rb', line 54

def any?
  pattern.nil?
end

#cover?(id) ⇒ Boolean

Parameters:

  • id (Symbol, String)

Returns:

  • (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_idsSet<Symbol>?

Returns:

  • (Set<Symbol>, nil)


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: &

Parameters:

  • another (IdMasklia, Set<Symbol>, Array<Symbol>, Hash<Symbol>, nil)

Returns:



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

Parameters:

  • id (String, Symbol)

Returns:



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_patternHash?

Returns:

  • (Hash, nil)


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