[prev in list] [next in list] [prev in thread] [next in thread]
List: ruby-talk
Subject: class methods like attr:
From: Gioele Barabucci <ml () gioelebarabucci ! com>
Date: 2006-01-21 22:28:28
Message-ID: 200601212308.35782.ml () gioelebarabucci ! com
[Download RAW message or body]
How can I create methods like "attr:" that can create methods and instance
variables?
I'd like to do this
class B < A
my_property :k, "K"
def test
p @k # should print "K"
p @@my_properties # should print ['k']
end
end
I tried with this (non-) solution
class A
def A.my_property(sym, val)
self.instance_eval {
@@my_properties ||= Array.new()
@@my_properties << sym.to_s
eval "@#{sym.id2name} = \"#{val}\""
# p @k1 # << this shows "K1.B" or "K1.C" as expected
}
end
end
but these tests showed me that I was wrong
class A
def test
p @@my_properties
end
end
class B < A
my_property :k1, "K1.B" # k1 is a string fixed to "K1"
my_property :k2, "K2.B"
def test
super # should be ['k1', 'k2']
p @k1 # should be "K1"
end
end
class C < A
my_property :k1, "K1.C"
def test
super # should be ['k1']
p @k1 # should be "K1.C"
end
end
A.new.test (should print nil or a warning) => ["k1", "k2", "k1"]
B.new.test (should print ['k1', 'k2'] 'K1.B') => ["k1", "k2", "k1"]
./at.rb:28: warning: instance variable @k1 not initialized
nil
A.new.test (should print nil or a warning) => ["k1", "k2", "k1"]
C.new.test (should print ['k1'] 'K1.C') => ["k1", "k2", "k1"]
./at.rb:36: warning: instance variable @k1 not initialized
nil
Any suggestion or idea?
--
Gioele <dev@gioelebarabucci.com>
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic