Skip to content

Instantly share code, notes, and snippets.

@ravelll
Created May 4, 2019 05:41
Show Gist options
  • Save ravelll/25cc217e4b82a5b602c1e295efb1c50a to your computer and use it in GitHub Desktop.
Save ravelll/25cc217e4b82a5b602c1e295efb1c50a to your computer and use it in GitHub Desktop.
### Inspect where a method is called
def foo(x, y)
p caller # Kernel#caller
# ...
end
### Inspect where a method is defined
# Where is obj.foo defined?
p obj.method(:foo).source_location # Method#source_location
### Output all methods will be called
trace = TracePoint.new(:call, :c_call) do |tp|
cls = tp.defined_class
m = if cls.singleton_class?
"#{cls.to_s[/#<Class:(.+)>/, 1]}.#{tp.method_id}"
else
"#{cls}##{tp.method_id}"
end
puts "#{m} (#{tp.path}:#{tp.lineno})"
end
trace.enable
# codes....
trace.disable
### Count the number of objects on memory
GC.start
ObjectSpace.each_object(Hash).count
### Inspect where a global variable is overwrote
trace_var(:$FOO) do |newval|
p caller.first
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment