From: Sean O'Halpin Date: 2008-08-24T10:37:53+09:00 Subject: Re: Passing parameters into a singleton class def? On Sun, Aug 24, 2008 at 2:09 AM, Doug Glidden <41mortimer@gmail.com> wrote: > Hi, > > I'm a little new to Ruby, so please feel free to suggest a completely > different and better way to do this, if you have one. I'm trying to > figure out a way to access a variable within a singleton class > definition that is defined outside the singleton class definition. > Basically, I want to be able to add new, user-defined instance variables > and readers and writers for the instance variables to an object. I can > do it fine if I construct the list of instance variables inline. Given > a definition of MyClass, of course, the following code works > beautifully: > > var = MyClass.new > class << var > attr_accessor :field1, :field2, :field3 > end > > However, I need to be able to build the list prior to doing the > singleton class definition (ideally, I want to be able to pass the list > of instance variables into an instance method and have it take care of > the singleton class definition on itself). This is the way code is > written right now: > > class MyClass > ... > > def add_fields(*field_list) > class << self > attr accessor *field_list > end > end > end > > I've also tried the following in irb (identical to the above code that > works, except that the list of fields is assigned to a variable instead > of being constructed inline): > > var = MyClass.new > list = :field1, :field2, :field3 > class << var > attr_accessor list > end > > Both throw an error because field_list is not defined within the > singleton class definition? Am I making a simple mistake, or should I > be doing this differently? > > Thanks, > Doug G. > -- > Posted via http://www.ruby-forum.com/. > > Something like this? class A end a = A.new fields = [:a, :b] (class << a; self; end).class_eval do attr_accessor *fields end a.a = 1 a.b = 2 p a b = A.new b.a = 3 __END__ # rt.rb:13: undefined method `a=' for # (NoMethodError) Regards, Sean