This question already has an answer here:
Is there any way in Ruby for a class to know how many instances of it exist and can it list them?
Here is a sample class:
class Project
attr_accessor :name, :tasks
def initialize(options)
@name = options[:name]
@tasks = options[:tasks]
end
def self.all
# return listing of project objects
end
def self.count
# return a count of existing projects
end
end
Now I create project objects of this class:
options1 = {
name: 'Building house',
priority: 2,
tasks: []
}
options2 = {
name: 'Getting a loan from the Bank',
priority: 3,
tasks: []
}
@project1 = Project.new(options1)
@project2 = Project.new(options2)
What I would like is to have class methods like Project.all
and Project.count
to return a listing and count of current projects.
How do I do this?
Maybe this will work:
But you will have to manually destroy these objects. Maybe other solution can be build based on ObjectSpace module.
You can use the
ObjectSpace
module to do this, specifically theeach_object
method.For completeness, here's how you would use that in your class (hat tip to sawa)
One way to do is to keep track of it as and when you create new instances.
If you want to use
ObjectSpace
, then its