Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Ruby Modules!
You have completed Ruby Modules!
Preview
In this video, we begin to implement our inventory stock counts.
Code Samples
We set up a couple of helper methods in our Inventoryable
class to keep up with stock counts:
module Inventoryable
def stock_count
@stock_count ||= 0
end
def stock_count=(number)
@stock_count = number
end
def in_stock?
stock_count > 0
end
end
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
So when we last left off we had just
created this inventoryable module, and
0:00
we're going to use that in all of
our different product classes.
0:04
So let's go ahead and
first off we're just going to include it
0:09
in the shirt class, and
that'll be a good start.
0:14
So now, let's go ahead and
make a couple of attribute methods for
0:20
setting the stock status of an item.
0:25
So we want to be able to say,
okay this is how many
0:28
units are in stock for a shirt,
a pair of pants, an accessory, whatever.
0:34
Now we're gonna define this
method called stock_count,
0:41
and stock count is going to
work very similarly to our
0:48
instances class method that we used
over in the extend tracking module.
0:53
So we're just going to
conditionally set it to zero.
1:00
Now what this is going to do is
initialize a variable called stock_count,
1:07
and set it to zero if it
does not already exist.
1:12
If it does exist,
the variable will be returned.
1:15
Now because we've done that we also
need something to set the stock count.
1:20
So we define a method called
stock_count=(number), and
1:25
then we'll just say the stock count
now equals the number not zero.
1:31
So let's go ahead and
test this out really quickly.
1:38
We'll say shirt1.stock_count = 10.
1:41
Now we can print these both out.
1:46
And we'll say shirt1.stock_count,
and we're going to copy and
1:54
paste that line and
we're going to say Shirt 2 stock count,
2:00
and we should see ten and
zero if we run this.
2:05
And we do, and
that's exactly what we want.
2:12
So when we put a new item in
the inventory, if we don't explicitly
2:16
set the stock count we're going to
think that we have zero in stock.
2:20
And this makes sense.
2:24
So now let's go ahead and
write another method to see whether or
2:28
not something is in stock.
2:32
And we're going to say it's in stock if
the stock count is greater than zero.
2:37
And we don't need to replay these,
but we'll go ahead and
2:46
just say shirt one in stock.
2:49
And the same thing for Shirt 2.
2:57
And that looks pretty good.
3:08
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up