Skip to content

Instantly share code, notes, and snippets.

@trans
Created February 2, 2014 17:08
Show Gist options
  • Save trans/8771452 to your computer and use it in GitHub Desktop.
Save trans/8771452 to your computer and use it in GitHub Desktop.
Very simply implementation of object reflection.
# NOTE: This code was part of Ruby Facets standard library, but
# it has been deprecated in favor of more sophisticated
# implementations, such as the `instance` and `mirror` gems.
module ObjectSpace
# Reflection ensures that information about an object
# is actual according to Ruby's Kernel definitions, just
# in case such methods have been overridden.
#
# ObjectSpace.reflect("object").object_id
#
# There is also a global short-cut for this method to ease
# meta-programming with it.
#
# $ref["object"].class
#
# Typically this method will be used to gather the object's
# id, as in the example given, or it's class, but any Kernel
# method can be used.
#
# Care should be taken in utilizing this technique. In most
# cases it is not needed, but in certain cases is useful
# for improving the robustness of meta-programming solutions.
#
# Note that this is also equivalent to using Facets `as(Kernel)` ...
#
# "object".as(Kernel).object_id
#
# But obviously, in this case there is the risk that `#as` has
# be overridden too.
#
def self.reflect(obj)
Reflector.new(obj)
end
# Reflector class can be used to get real information about a class
# even if it has overriden important Kernel methods, e.g. object_id.
#
class Reflector < BasicObject
def initialize(obj)
@obj = obj
end
def method_missing(op, *args, &yld)
Kernel.instance_method(op).bind(@obj).call(*args, &yld)
end
end
end
# Shorcut for +ObjectSpace.reflect+.
#
# Examples
#
# $ref[obj].object_id
#
$ref = lambda do |obj|
ObjectSpace.reflect(obj)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment