Skip to content

Instantly share code, notes, and snippets.

@pocke
Created July 6, 2019 09:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocke/7b14f4876701c3cee639da8b4b15a6d2 to your computer and use it in GitHub Desktop.
Save pocke/7b14f4876701c3cee639da8b4b15a6d2 to your computer and use it in GitHub Desktop.
module B
extend self
@enabled = false
def enable!
return if @enabled
clear
@enabled = true
@trace = TracePoint.new(:call, :c_call, :return, :c_return) do |tp|
handle(tp)
end
@trace.enable
end
def binding_of_caller(n)
offset = 2
@bindings[-(n + offset)]
end
def disable!
return unless @enabled
clear
@enabled = false
@trace.disable
end
private def clear
@bindings = []
end
private def handle(tp)
case tp.event
when :call, :c_call
@bindings.push tp.binding
when :return, :c_return
@bindings.pop
else
raise "[bug] unknown event: #{tp.event}"
end
end
end
B.enable!
def a
var = 10
b
puts var
end
def b
c
end
def c
B.binding_of_caller(2).eval('var = :hello')
end
a() # hello
B.disable!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment