Last Updated: February 25, 2016
·
141
· atovt

Dynamic instance attributes

class Foo
  def method_missing(m, *params)
    name = m.to_s
    if name[-1] == '='
      mod = Module.new do
        attr_accessor name[0..-2]
      end
      self.extend mod
      self.send(m,*params)
    else
      throw "no method"
    end
  end
end

Every instance of class Foo will have it's own set of attributes as soon as they will be set like this:

x = Foo.new
# x.f # no method
x.f = 10
x.f # 10
# Foo.new.f # no method