Class: BlockKit::TypedSet

Inherits:
Set
  • Object
show all
Defined in:
lib/block_kit/typed_set.rb

Overview

Custom array class that maintains type constraints during mutation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(item_type, enum = nil) ⇒ TypedSet

Returns a new instance of TypedSet.



8
9
10
11
12
13
14
15
16
17
# File 'lib/block_kit/typed_set.rb', line 8

def initialize(item_type, enum = nil)
  # Only support scalar item types for now
  unless item_type.respond_to?(:type) && !item_type.type.start_with?("block_kit_")
    raise ArgumentError, "Only scalar item types are supported"
  end

  @item_type = item_type

  super(enum&.map { |item| item_type.cast(item) }&.compact)
end

Instance Attribute Details

#item_typeObject (readonly)

Returns the value of attribute item_type.



6
7
8
# File 'lib/block_kit/typed_set.rb', line 6

def item_type
  @item_type
end

Instance Method Details

#&(other) ⇒ Object Also known as: intersection



41
42
43
44
45
46
47
48
49
50
# File 'lib/block_kit/typed_set.rb', line 41

def &(other)
  n = self.class.new(item_type)
  if other.is_a?(Set)
    each { |item| n.add(item) if other.include?(item) }
  else
    do_with_enum(other) { |item| n.add(item) if include?(item) }
  end

  n.compact
end

#add(item) ⇒ Object Also known as: <<

Override methods that modify the set to ensure type constraints.



20
21
22
# File 'lib/block_kit/typed_set.rb', line 20

def add(item)
  super(item_type.cast(item)).tap(&:compact!)
end

#collect!(&block) ⇒ Object



33
34
35
# File 'lib/block_kit/typed_set.rb', line 33

def collect!(&block)
  super { |item| item_type.cast(yield(item)) }.compact
end

#compactObject



58
59
60
# File 'lib/block_kit/typed_set.rb', line 58

def compact
  dup.tap(&:compact!)
end

#compact!Object



53
54
55
56
# File 'lib/block_kit/typed_set.rb', line 53

def compact!
  delete(nil) { return nil }
  self
end

#inspectObject



62
63
64
# File 'lib/block_kit/typed_set.rb', line 62

def inspect
  super.tap { |str| str.sub!("Set", "TypedSet[#{item_type.type}]") }
end

#map!(&block) ⇒ Object



29
30
31
# File 'lib/block_kit/typed_set.rb', line 29

def map!(&block)
  super { |item| item_type.cast(yield(item)) }.compact
end

#merge(other) ⇒ Object



37
38
39
# File 'lib/block_kit/typed_set.rb', line 37

def merge(other)
  super(other.map { |item| item_type.cast(item) }).compact
end

#replace(other) ⇒ Object



25
26
27
# File 'lib/block_kit/typed_set.rb', line 25

def replace(other)
  super(other.map { |item| item_type.cast(item) }.compact)
end