views:

150

answers:

1

I'm trying to do an instance_eval followed by a attr_accessor inside initialize, and I keep getting this: `initialize': undefined method 'attr_accessor'. Why isn't this working?

The code looks kind of like this:

class MyClass
   def initialize(*args)
      instance_eval "attr_accessor :#{sym}"
   end
end
+6  A: 

You can't call attr_accessor on the instance, because attr_accessor is not defined as an instance method of MyClass. It's only available on modules and classes. I suspect you want to call attr_accessor on the instance's metaclass, like this:

class MyClass
  def initialize(varname)
    class <<self
      self
    end.class_eval do
      attr_accessor varname
    end
  end
end

o1 = MyClass.new(:foo)
o2 = MyClass.new(:bar)
o1.foo = "foo" # works
o2.bar = "bar" # works
o2.foo = "baz" # does not work
sepp2k
class_eval is the same as putting it where you wrote self
johannes
No, it's not. `class <<self; ...;end` is not a closure. You wouldn't be able to access `varname` inside it, but you can access it in the `class_eval` block.
sepp2k