Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Counting classes created with `Class.new`
#!/usr/bin/env ruby
# Don't use this in production!
module ClassCounter
def self.extended (klass)
$stderr.puts("Injecting hacked `new' into `#{klass}'")
klass.instance_exec {@klass_count = 0}
end
def new (*)
super.tap do |klass|
@klass_count += 1
$stderr.puts("New class: #{klass} count: #@klass_count")
end
end
end
# Override Class::new.
Class.extend(ClassCounter)
# Test it out.
something = Class.new
another = Class.new
@ipmsteven

This comment has been minimized.

Copy link

@ipmsteven ipmsteven commented May 27, 2015

Awesome! 😄

one more question 😀

class Class
  alias oldNew  new
  def new(*args)
    print "Creating a new ", self.name, "\n"
    oldNew(*args)
  end
end

class Name
end

Name.new
# output: Creating a new Name

Class.new
# output: Creating a new Class

Calling Name.new will output Creating a new Name since we modify the instance method new of Class, but why the "class" method new also got effected and output Creating a new Class when I call Class.new?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment