BasicObject
BasicObject provides an abstract base class with no predefined methods, except for respond_to?, any method starting in __ (two underscore, like __id__) as well as any method starting with <tt>instance_</ttr>.
BasicObject is useful as a base class when writing classes that depend upon method_missing (e.g. dynamic proxies).
The patterns used to reserve methods are:
/^__/, /^instance/, /^object/, /\?$/, /^\W$/, 'initialize', 'initialize_copy', 'inspect', 'dup', 'clone', 'null'
By default these are the reserved methods:
== __as__ __id__ __class__ __self__ __send__ clone dup eql? equal? frozen? initialize inspect instance_eval instance_of? instance_variable_get instance_variable_set instance_variables is_a? kind_of? nil? null respond_to? tainted?
The special method #self allows access to the underlying object via a specialized Functor-style class called, BasicObject::Self. This binds the actual self to the subsequently called methods of Object instancea methods. So even though a method may no longer be defined for BasicObject it can still be called via this interface.
class A < BasicObject end a.__self__.class #=> A a.class #=> NoMethodError
EXCLUDE | = | [ /^__/, /^instance_/, /^object_/, /\?$/, /^\W$/, 'initialize', 'initialize_copy', 'inspect', 'dup', 'clone', 'null' |
Methods not to get rid of as they are either too important, or they are not
likely to get in the way (such as methods ending in ’?’).
In Ruby 1.9 BasicObject has only these methods: [ /^__/, "funcall", "send", "respond_to?", "equal?", "==", "object_id" ] |
Undef unwanted method as long as it doesn’t match anything in the EXCLUDE list.
[ show source ]
# File lib/facets/more/basicobject.rb, line 127 def self.hide(name) #if instance_methods.include?(name.to_s) and name !~ EXCLUDE #/^(#{EXCLUDE.join('|')})/ #if name !~ EXCLUDE and case name when *EXCLUDE # do nothing else #if ( public_instance_methods.include?(name.to_s) or # private_instance_methods.include?(name.to_s) or # protected_instance_methods.include?(name.to_s) # ) undef_method name rescue nil #end end end
This method is like #self, but allows any ancestor to act on behalf of self, not just Object.
[ show source ]
# File lib/facets/more/basicobject.rb, line 96 def __as__( ancestor ) Self.new( self, ancestor ) end
Returns the Self functor class, which can then be used to call Kernel/Object methods on the current object.
[ show source ]
# File lib/facets/more/basicobject.rb, line 89 def __self__ @__self__ ||= Self.new( self ) end
If the method isn’t defined and has the form ‘method’ then try sending ‘method’ to self-as-Object. Remember this will not have any effect if you override it!
[ show source ]
# File lib/facets/more/basicobject.rb, line 153 def method_missing( sym, *args, &blk ) if md = /^__(.+)__$/.match( sym.to_s ) __as__(Object).__send__( md[1], *args, &blk ) else super end end