I know there is should be a way to initialize class instance variable that added by a module via extend example:
module MyModule
def self.included(base)
base.extend ClassMethods
base.send :include, InstanceMethods
end
module ClassMethods
attr_accessor :count
def self.count
@count = 0
end
count
end
module InstanceMethods
def register
# self.class.count = 0 if self.class.count.nil?
self.class.count += 1
end
end
end
class Foo
include MyModule
private
def initialize
register
end
end
In ClassMethods should be a way to initialize count, but i always catch error "undefined method `+' for nil:NilClass" When i perform
f = Foo.new
No problem in module InstanceMethods if i uncomment line
# self.class.count = 0 if self.class.count.nil?
Work correctly!
attr_accessor :countdefines attributes acces for instance variables.includeis no longer a private method. Which means, no need tosendit. Justbase.include InstanceMethodsinitializeis by default private, so you can omit the explicitprivateinFoo.