I want to make a simple module that makes its including classes
self-countable.
Here is the code (that does not work, incidentally):
#---code
module Countable
@@counter = 0
def initialize
@@counter += 1
end
module ClassMethods
def population
return @@counter
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
class User
include Countable
end
User.new
User.new
puts User.population
#---code
The error message says that the @@counter class variable is not
initialized in Countable::ClassMethods (so in the population method).
Obviously, this @@counter variable is not the same as the one that is
declared when including Countable, since User.new works as expected.
Can someone explain me why and how to solve this?
···
--
Posted via http://www.ruby-forum.com/.