Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use attr_accessor inside initialize?

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
like image 584
Geo Avatar asked Nov 14 '09 17:11

Geo


People also ask

What is the use of attr_accessor in Ruby?

To access and modify data, we use the attr_reader and attr_writer . attr_accessor is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.

How does attr_reader work in Ruby?

Summary. attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.

What is Attr_accessible?

virtual attribute – an attribute not corresponding to a column in the database. attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.

What is attr_reader?

Using attr_reader , you can read the variable name outside the class scope.


1 Answers

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
like image 176
sepp2k Avatar answered Nov 08 '22 09:11

sepp2k