{ |one, step, back| } 1 of 1 article Syndicate: full/short

Starting with a Blank Slate   21 May 04
[ print link all ]
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

Now, try this with the proxy object:

  n = Proxy.new(1)
  puts (n+5)
  puts "1.id = #{1.id}"
  puts "n.id = #{n.id}"
  puts "n.__id__ = #{n.__id__}"

Here’s the output:

  $ ruby blankslatedemo.rb
  Sending +(5) to obj
  6
  1.id = 3
  Sending id() to obj
  n.id = 3
  n.__id__ = 537806934


blog comments powered by Disqus

 

Formatted: 16-May-12 22:01
Feedback: jim@weirichhouse.org