Class: Bag
Instance Method Summary collapse
-
#add(amount, item) ⇒ Object
> Insertions / Deletions.
-
#add_all(other) ⇒ Object
> Should follow.
-
#each(&block) ⇒ Object
> Iterating.
- #empty? ⇒ Boolean
-
#has?(amount, item) ⇒ Boolean
> Booleans Do we have the item?.
-
#initialize ⇒ Bag
constructor
Create the bag.
-
#print ⇒ Object
> Formating Let me know how many things are in my bag man.
-
#remove(amount, item) ⇒ Object
Someone bought my things.
- #remove_all(other) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize ⇒ Bag
Create the bag
7 8 9 |
# File 'lib/inventory/bag.rb', line 7 def initialize @bag = Hash.new end |
Instance Method Details
#add(amount, item) ⇒ Object
> Insertions / Deletions
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/inventory/bag.rb', line 27 def add(amount, item) unless amount > 0 raise Exceptions::NotEnoughError "Value must be greater than 0" end if Thing.exists?(:name => item) # find it in the database the_item = Thing.find_by(name: item) the_item.amount += amount the_item.save else @bag[item] = amount Thing.create(:name => item, :amount => amount) end end |
#add_all(other) ⇒ Object
> Should follow
45 46 47 48 49 |
# File 'lib/inventory/bag.rb', line 45 def add_all(other) other.each do |item, amount| self.add(amount, item) end end |
#each(&block) ⇒ Object
> Iterating
75 76 77 |
# File 'lib/inventory/bag.rb', line 75 def each(&block) @bag.each(&block) end |
#empty? ⇒ Boolean
22 23 24 |
# File 'lib/inventory/bag.rb', line 22 def empty? @bag.size == 0 end |
#has?(amount, item) ⇒ Boolean
> Booleans
Do we have the item?
17 18 19 20 |
# File 'lib/inventory/bag.rb', line 17 def has?(amount, item) Thing.exists?(:name => item) and Thing.find_by(name: item).amount >= amount #@bag.has_key?(item) and @bag[item] >= amount end |
#print ⇒ Object
> Formating
Let me know how many things are in my bag man.
81 82 83 84 85 86 87 88 89 |
# File 'lib/inventory/bag.rb', line 81 def print buffer = [] Thing.find_each do |a| if a.amount > 0 buffer << " #{a.name}: #{a.amount}" end end buffer end |
#remove(amount, item) ⇒ Object
Someone bought my things
52 53 54 55 56 57 58 59 60 61 |
# File 'lib/inventory/bag.rb', line 52 def remove(amount, item) if !self.has?(amount, item) puts "not enough" else # find it in the database the_item = Thing.find_by(name: item) the_item.amount -= amount the_item.save end end |
#remove_all(other) ⇒ Object
63 64 65 66 67 68 69 70 71 72 |
# File 'lib/inventory/bag.rb', line 63 def remove_all(other) if @bag.empty? puts "empty bag" return else other.each do |item, amount| self.remove(amount, item) end end end |
#size ⇒ Object
11 12 13 |
# File 'lib/inventory/bag.rb', line 11 def size @bag.size end |