Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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.
#!/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.