Skip to content

Instantly share code, notes, and snippets.

@pjones
Created May 26, 2015 19:28
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 pjones/fddae91247a37cda521c to your computer and use it in GitHub Desktop.
Save pjones/fddae91247a37cda521c to your computer and use it in GitHub Desktop.
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
Copy link

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