Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirnaeth/9e810cdf915d15ebcbde06a0d8b76b0c to your computer and use it in GitHub Desktop.
Save nirnaeth/9e810cdf915d15ebcbde06a0d8b76b0c 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.
#!/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)