Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Last active December 13, 2015 19:48
Embed
What would you like to do?
Don't even think about this.
$pointsz = Hash.new(0)
class Class
method_blacklist = [:method_added, :===, :to_s, :send, :public_methods, :new]
methods_to_redefine = public_methods.reject{|m| method_blacklist.include? m }
methods_to_redefine.each do |m|
new_name = "__lol_omg_#{m}"
define_method m do |*args, &blk|
__lol_omg_puts "#{m} was called with #{args}"
$pointsz[m] += 1
send(new_name, *args, &blk)
end
alias_method new_name, m
end
end
class Module
method_blacklist = [:method_added, :===, :to_s, :send, :public_methods]
methods_to_redefine = public_methods.reject{|m| method_blacklist.include? m }
methods_to_redefine.each do |m|
new_name = "__lol_omg_#{m}"
define_method m do |*args, &blk|
__lol_omg_puts "#{m} was called with #{args}"
$pointsz[m] += 1
send(new_name, *args, &blk)
end
alias_method new_name, m
end
end
module Kernel
method_blacklist = BasicObject.public_methods
methods_to_redefine = public_methods
.reject{|m| method_blacklist.include? m }
.reject{|m| m.to_s.start_with?("__lol_omg_") }
methods_to_redefine.each do |m|
new_name = "__lol_omg_#{m}"
alias_method new_name, m
define_method m do |*args, &blk|
__lol_omg_puts "#{m} was called with #{args}"
$pointsz[m] += 1
send(new_name, *args, &blk)
end
end
end
at_exit do
__lol_omg_puts "SUMMARY: "
__lol_omg_puts "method\t\tcalls"
$pointsz.each do |k, v|
__lol_omg_puts "#{k}\t\t#{v}"
end
end
@steveklabnik
Copy link
Author

I particularly enjoy line 41, where I had to check that I didn't try to redefine things I already redefined....

@colindean
Copy link

Do I correctly understand that this basically counts messages sent/methods called?

@tammersaleh
Copy link

My favorite is the use of __lol_omg_puts.

@jpfuentes2
Copy link

Why not use __send__ instead? http://stackoverflow.com/a/4658359/310275

@steveklabnik
Copy link
Author

@colindean yes

@tsaleh still working on it, might make them have spaces in the name ;)

@jpfuentes2 to call the original ones? I could.

@henrik
Copy link

henrik commented Feb 16, 2013

- methods_to_redefine = public_methods.reject{|m| method_blacklist.include? m }
+ methods_to_redefine = public_methods - method_blacklist

@henrik
Copy link

henrik commented Feb 16, 2013

Also, you could possibly use set_trace_func for this.

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