Last active
December 14, 2015 05:19
-
-
Save bil-bas/5034125 to your computer and use it in GitHub Desktop.
This ends up with horrible infinite looping, so is a bit broken ;)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ObjectSpace | |
class << self | |
def find_references(target) | |
each_object.select {|obj| references?(obj, target) } | |
end | |
def references?(object, target) | |
contains = case object | |
when Hash | |
object.any? {|k, v| references?(k, target) || references?(v, target) } | |
when Enumerable | |
object.any? {|e| references?(e, target) } | |
when Proc | |
if object.source_location.nil? | |
false # C code | |
else | |
locals = object.binding.eval("local_variables") | |
locals.any? {|l| object.binding.eval(l.to_s).equal? target } | |
end | |
end | |
contains || | |
object.instance_variables.any? {|v| object.instance_variable_get(v).equal? target } || | |
((object.is_a? Class) && object.class_variables.any? {|v| object.class_variable_get(v).equal? target }) | |
end | |
end | |
end | |
x = Object.new | |
ObjectSpace.find_references x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment