public

Example for adding functionality to instances of a class which needs help from class methods of the same class. Use two modules - one for instance methods and one for class methods.

  • Download Gist
automated_class_instance_collaboration.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#!/usr/bin/ruby -w
 
module Foo
module Foo4Class
def reset_instance_count
@instance_count = 0
end
 
def new(*a, &b)
super.tap { @instance_count += 1 }
end
 
def instance_count
@instance_count
end
end
 
def shout_instance_count
printf "There have been %d of us created!\n", self.class.instance_count
end
 
# setup mechanics
def self.included(cl)
cl.extend(Foo4Class).reset_instance_count
end
end
 
 
class Bar
include Foo
end
 
Array.new(10) { Bar.new }.each(&:shout_instance_count)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.