Class: Haversack::ItemCollection

Inherits:
Array
  • Object
show all
Defined in:
lib/haversack/itemcollection.rb

Direct Known Subclasses

Sack

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, &block) ⇒ ItemCollection

Returns a new instance of ItemCollection.



4
5
6
7
8
9
10
11
12
13
# File 'lib/haversack/itemcollection.rb', line 4

def initialize(data, &block)
  if !block_given?
    raise ArgumentError, "expected #{data} to contain only elements of class Haversack::Item" unless data.is_a?(Array) && ItemCollection.only_items?(data)
  end

  @size   = self.size
  @weight = self.weight

  block_given? ? super(data, block) : super(data)
end

Class Method Details

.only_items?(data) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/haversack/itemcollection.rb', line 28

def self.only_items?(data)
  data.all? { |el| el.is_a? Haversack::Item }
end

Instance Method Details

#push(obj) ⇒ Object



23
24
25
26
# File 'lib/haversack/itemcollection.rb', line 23

def push(obj)
  raise Haversack::KnapsackContentError unless obj.is_a? Haversack::Item
  super
end

#sizeObject



15
16
17
# File 'lib/haversack/itemcollection.rb', line 15

def size
  map(&:size).sum
end

#weightObject



19
20
21
# File 'lib/haversack/itemcollection.rb', line 19

def weight
  map(&:weight).sum
end