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 learn a little trick with extending and including something at the same time.
Code Samples
module Inventoryable
def self.included(klass)
klass.extend(ClassMethods)
end
module ClassMethods
def create(attributes)
object = new(attributes)
instances.push(object)
return object
end
def instances
@instances ||= []
end
end
def stock_count
@stock_count ||= 0
end
def stock_count=(number)
@stock_count = number
end
def in_stock?
stock_count > 0
end
end
class Shirt
include Inventoryable
attr_accessor :attributes
def initialize(attributes)
@attributes = attributes
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
Now what we're gonna do is take the same
pattern that we used in the tracking
0:00
module to do this create and
return instances.
0:02
So, we're gonna do this
in a tricky little way.
0:08
We're gonna do it inside of another
module, inside of Inventoryable.
0:11
We're gonna call this ClassMethods
0:15
because these are going to go on
the class of what we want inventoried.
0:19
So let's go ahead and
write our create method.
0:25
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