On Sat, 24 Feb 2007 14:08:19 +0100, Robert Klemme wrote:

> On 24.02.2007 13:52, Tim Becker wrote:
>> Hi,
>> 
>> I'm trying to write a class with a method to extend instances of itself
>> to contain additional accessors. I thought using `class << self` would
>> be the most elegant way to go about it, but I'm running into some
>> problems. To illustrate:
>> 
>> class Test
>>  # takes an array of symbols to add to the instance. def add syms
>>    syms.each { |sym|
>>      @@__tmp = sym
>>      $__tmp = sym
>>      class << self
>>        #attr_accessor sym  # this would be my preferance, but sym
>> isn't in scope here
>>        #attr_accessor $__tmp  # this works, but uses globals
>>        attr_accessor @@__tmp   # this is nearly as bad as using globals
>>      end # <<
>>    } # each
>>  end # add
>> end # Test
>> Any ideas? Am I missing something?
> 
> See above.  Apart from that you could simply use OpenStruct or inherit
> OpenStruct which does all this for you already automagically:
> 
> irb(main):013:0> require 'ostruct'
> => true
> irb(main):014:0> f=OpenStruct.new
> => #<OpenStruct>
> irb(main):015:0> f.bar=10
> => 10
> irb(main):016:0> f.bar
> => 10
> 
> Major difference is that you do not explicitly control accessor creation
> but automatically get *all* - even spelling errors.

Test=Struct.new(*syms)
or
Test=Struct.new(:foo,:bar,:baz)

This will guard you against spelling errors.

--Ken

-- 
Ken Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/