zsquare
zsquare

Reputation: 10146

Define dynamic setter using method_missing

I want to be able to use in my code the following construct:

p obj.graph_XYZ
obj.graph_XYZ << obj2

Here I want to handle any getter/setter beginning with graph_

I can hook onto the getters, but method_missing picks the getter even when I use obj.graph_XYZ << obj2. Any inputs as to what i may be doing wrong?

Upvotes: 1

Views: 833

Answers (1)

ian
ian

Reputation: 12251

Something like this might work for you?

$ irb                                                                                      

class A
  attr_accessor :xyz
end
=> nil
a = A.new
=> #<A:0x0000010096bc88>
a.xyz
=> nil
a.xyz << 2
NoMethodError: undefined method `<<' for nil:NilClass
  from (irb):6
  from /Users/iain/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'
a.xyz = [ ]
=> []
a.xyz << 2
=> [2]
a.xyz
=> [2]
class A
  def method_missing( name, *args )
    return super( name, *args ) unless name.to_s =~ /^graph/  
    words = name.to_s.split( "_" )
    words.shift # get rid of graph_

    # now do what you like
    # ...
    if (instance_variable_get "@#{words.first.downcase}").nil?
      instance_variable_set "@#{words.first.downcase}", []
    end

    (instance_variable_get "@#{words.first.downcase}")
  end
end
=> nil
a = A.new
=> #<A:0x00000100844a58>
a.graph_XYZ
=> []
a.graph_XYZ << 2
=> [2]
a.graph_XYZ
=> [2]

Upvotes: 1

Related Questions