Here’s a quick Ruby tip. All Ruby classes ultimately inherit from the
Object class. This means that every object gets about 40 methods from the
Object class without doing anything extra.
Sometimes, however, you don’t want to start with all those methods.
I’m thinking of proxy classes that use method_missing to
forward messages to another object. Methods defined by Object (actually
Kernel, but lets not worry about that) will not be forwarded because they
are not missing in the proxy.
This is easy to fix. Create a BlankSlate class like this
…
class BlankSlate
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
end
BlankSlate is a class
with no instance methods except for __send__ and __id__.
Now we can create a proxy object by inheriting from BlankSlate …
class Proxy < BlankSlate
def initialize(obj)
@obj = obj
end
def method_missing(sym, *args, &block)
puts "Sending #{sym}(#{args.join(',')}) to obj"
@obj.__send__(sym, *args, &block)
end
end