Class: Vident2::Stimulus::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/vident2/stimulus/collection.rb

Overview

Tiny aggregation wrapper for the plural ‘stimulus_<kind>s` parsers. Parametric over `kind`: the kind decides the per-element combining rule via its value class’s ‘.to_data_hash`. Users interact with this object by splatting `**component**component.stimulus_targets(…)` into a `data:` option on a tag, so `#to_h` is the single required shape.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(kind:, items:) ⇒ Collection

Returns a new instance of Collection.



15
16
17
18
# File 'lib/vident2/stimulus/collection.rb', line 15

def initialize(kind:, items:)
  @kind = kind
  @items = items.freeze
end

Instance Attribute Details

#itemsObject (readonly)

Returns the value of attribute items.



13
14
15
# File 'lib/vident2/stimulus/collection.rb', line 13

def items
  @items
end

#kindObject (readonly)

Returns the value of attribute kind.



13
14
15
# File 'lib/vident2/stimulus/collection.rb', line 13

def kind
  @kind
end

Instance Method Details

#any?Boolean

Returns:

  • (Boolean)


25
# File 'lib/vident2/stimulus/collection.rb', line 25

def any? = @items.any?

#each(&block) ⇒ Object



20
# File 'lib/vident2/stimulus/collection.rb', line 20

def each(&block) = @items.each(&block)

#empty?Boolean

Returns:

  • (Boolean)


24
# File 'lib/vident2/stimulus/collection.rb', line 24

def empty? = @items.empty?

#lengthObject



23
# File 'lib/vident2/stimulus/collection.rb', line 23

def length = @items.size

#merge(other) ⇒ Object



34
35
36
37
38
39
# File 'lib/vident2/stimulus/collection.rb', line 34

def merge(other)
  unless other.is_a?(self.class) && other.kind == @kind
    raise ArgumentError, "Collection#merge: can only merge with same-kind Collection"
  end
  self.class.new(kind: @kind, items: @items + other.items)
end

#sizeObject



22
# File 'lib/vident2/stimulus/collection.rb', line 22

def size = @items.size

#to_aObject



21
# File 'lib/vident2/stimulus/collection.rb', line 21

def to_a = @items.dup

#to_hObject Also known as: to_hash

Delegates to the kind’s ‘.to_data_hash` — same path AttributeWriter uses at render time.



29
30
31
# File 'lib/vident2/stimulus/collection.rb', line 29

def to_h
  @kind.value_class.to_data_hash(@items)
end