Sha256: fff4a46da060b64c3ca5220efbb74e26b34770581f96dc3564c5779d1c9ae2a5

Contents?: true

Size: 1.86 KB

Versions: 13

Compression:

Stored size: 1.86 KB

Contents

# TITLE:
#
#   Reflection
#
# SUMMARY:
#
#   Provides externailze, safe access to an object's meta-information.
#
# COPYRIGHT:
#
#   Copyright (c) 2006 Thomas Sawyer
#
# LICENSE:
#
#   Ruby License
#
#   This module is free software. You may use, modify, and/or redistribute this
#   software under the same terms as Ruby.
#
#   This program is distributed in the hope that it will be useful, but WITHOUT
#   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#   FOR A PARTICULAR PURPOSE.
#
# AUTHORS:
#
#   - Thomas Sawyer


#
class << ObjectSpace
  alias_method :[], :_id2ref
end

#
class ObjectReflection

  REFLECTION_METHODS = [
    :object_id, :class, :methods, :send
  ] + Kernel.instance_methods.select{ |m| m =~ /^object_/ }

  def initialize(object)
    @self = object
    @meta = REFLECTION_METHODS.inject({}) do |rproc, meth|
      rproc[meth.to_sym] = Kernel.instance_method(meth).bind(@self)
      rproc
    end
  end

  #

  def id
    @meta[:object_id].call
  end

  REFLECTION_METHODS.each do |meth|
    meth = meth[7..-1] if meth =~ /^object_/
    module_eval %{
      def #{meth}(*a,&b)
        rproc[:#{meth}].call(*a,&b)
      end
    }
  end

end

#
class InstanceReflection < ObjectReflection

  REFLECTION_METHODS = [
    :send
  ] + Kernel.instance_methods.select{ |m| m =~ /^instance_/ }

  def initialize(object)
    @self = object
    @meta = REFLECTION_METHODS.inject({}) do |rproc, meth|
      rproc[meth.to_sym] = Kernel.instance_method(meth).bind(@self)
      rproc
    end
  end

  REFLECTION_METHODS.each do |meth|
    meth = meth[7..-1] if meth =~ /^instance_/
    module_eval %{
      def #{meth}(*a,&b)
        rproc[:#{meth}].call(*a,&b)
      end
    }
  end

end


module Kernel

  def object
    @_object_reflection ||= ObjectReflection.new(self)
  end

  def instance
    @_instance_reflection ||= InstanceReflection.new(self)
  end

end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
facets-2.0.0 lib/more/facets/reflection.rb
facets-2.0.1 lib/more/facets/reflection.rb
facets-2.0.2 lib/more/facets/reflection.rb
facets-2.0.5 lib/more/facets/reflection.rb
facets-2.1.0 lib/more/facets/reflection.rb
facets-2.1.2 lib/more/facets/reflection.rb
facets-2.0.3 lib/more/facets/reflection.rb
facets-2.0.4 lib/more/facets/reflection.rb
facets-2.1.1 lib/more/facets/reflection.rb
facets-2.3.0 lib/more/facets/reflection.rb
facets-2.1.3 lib/more/facets/reflection.rb
facets-2.2.0 lib/more/facets/reflection.rb
facets-2.2.1 lib/more/facets/reflection.rb