T
Tim Becker
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
t = Test.new
t.add [:thingie, :thingie2]
t.thingie="whatever"
t.thingie2="bla"
puts t.thingie
puts t.thingie2
I don't like the idea of using globals to transport the symbol
information and the class members approach is nearly as bad
(synchronization issues mainly, apart from elegance). But I can't
think of another way to transport dynamic data into the `class<<self`
block.
Alternatives would be to handle this using `method_missing` though
that wouldn't just affect a single instance or using `eval` which
would involve executing strings I'm banging together.
Another thing I tried was:
...
self.class.attr_accessor sym
...
but that doesn't work because `attr_accessor` is private (contrary to
what it says in the documentation...)
Any ideas? Am I missing something?
-tim
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
t = Test.new
t.add [:thingie, :thingie2]
t.thingie="whatever"
t.thingie2="bla"
puts t.thingie
puts t.thingie2
I don't like the idea of using globals to transport the symbol
information and the class members approach is nearly as bad
(synchronization issues mainly, apart from elegance). But I can't
think of another way to transport dynamic data into the `class<<self`
block.
Alternatives would be to handle this using `method_missing` though
that wouldn't just affect a single instance or using `eval` which
would involve executing strings I'm banging together.
Another thing I tried was:
...
self.class.attr_accessor sym
...
but that doesn't work because `attr_accessor` is private (contrary to
what it says in the documentation...)
Any ideas? Am I missing something?
-tim