Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

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.

View automated_class_instance_collaboration.rb
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.