views:

50

answers:

1

I have a class Wrapper that supports adding options that you can then look up later. It stores these options in an internal hash @dict.

w = Wrapper.new
w.foo # => NameError
w.foo = 10
w.foo # => 10

How can I write a method_missing for Wrapper so that I can support nested calls on @dict?

w = Wrapper.new
w.foo.bar.baz = 1000
w.foo.bar.baz # => 1000
+4  A: 

If this isn't what you are looking for, leave a comment.

class Wrapper
  def initialize(d={})
    @dict = d
  end

  def method_missing(method, *args)
    if method.to_s =~ /=$/
      @dict[method.to_s.match(/^(.*)=$/)[1].to_sym] = args.first
    else
      @dict[method] ||= Wrapper.new
    end
  end
end

w = Wrapper.new
w.foo = 5
w.foo #=> 5
w.x.y.z = 32
w.x.y.w = 43
w.x.y.z #=> 32
w.x.y.w #=> 43
Adrian
Does this support OP's chaining request?
Jeriko
@Jeriko - Look at the lines at the end. Yes.
Adrian