Last active
May 12, 2017 15:49
-
-
Save rklemme/7213313 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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