Class: Sack
Instance Attribute Summary collapse
Instance Method Summary
collapse
only_items?, #size, #weight
Constructor Details
#initialize(data, capacity:, max_weight:, &block) ⇒ Sack
Returns a new instance of Sack.
8
9
10
11
12
13
14
15
16
17
|
# File 'lib/haversack/sack.rb', line 8
def initialize(data, capacity:, max_weight:, &block)
@capacity = capacity
@max_weight = max_weight
block_given? ? super(data, &block) : super(data)
raise Haversack::KnapsackCapacityExceededError if contents_exceed_capacity?
raise Haversack::KnapsackWeightExceededError if contents_exceed_weight?
end
|
Instance Attribute Details
#capacity ⇒ Object
Returns the value of attribute capacity.
5
6
7
|
# File 'lib/haversack/sack.rb', line 5
def capacity
@capacity
end
|
#max_weight ⇒ Object
Returns the value of attribute max_weight.
6
7
8
|
# File 'lib/haversack/sack.rb', line 6
def max_weight
@max_weight
end
|
Instance Method Details
#available_capacity ⇒ Object
23
24
25
|
# File 'lib/haversack/sack.rb', line 23
def available_capacity
empty? ? @capacity : (@capacity - size)
end
|
#available_weight ⇒ Object
19
20
21
|
# File 'lib/haversack/sack.rb', line 19
def available_weight
empty? ? @max_weight : (@max_weight - weight)
end
|
#exceeds_capacity?(item) ⇒ Boolean
39
40
41
|
# File 'lib/haversack/sack.rb', line 39
def exceeds_capacity?(item)
!fits_capacity?(item)
end
|
#exceeds_weight?(item) ⇒ Boolean
31
32
33
|
# File 'lib/haversack/sack.rb', line 31
def exceeds_weight?(item)
!fits_weight?(item)
end
|
#fits_capacity?(item) ⇒ Boolean
35
36
37
|
# File 'lib/haversack/sack.rb', line 35
def fits_capacity?(item)
item.size <= available_capacity
end
|
#fits_item?(item) ⇒ Boolean
Also known as:
fits?
43
44
45
|
# File 'lib/haversack/sack.rb', line 43
def fits_item?(item)
item.is_a?(Haversack::Item) && fits_capacity?(item) && fits_weight?(item)
end
|
#fits_weight?(item) ⇒ Boolean
27
28
29
|
# File 'lib/haversack/sack.rb', line 27
def fits_weight?(item)
item.weight <= available_weight
end
|
#push(item) ⇒ Object
TODO: Describe which constraint failed
48
49
50
|
# File 'lib/haversack/sack.rb', line 48
def push(item)
fits_item?(item) ? super : raise(Haversack::KnapsackContentError)
end
|