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
Written by Attila Tovt
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#