get self as invoking class in parent in Ruby -
my first class has constant. want make work somehow dynamic value.
class post < activerecord::base test = ["#{self.name}", "test1"] end class fakepost < post end in rails console trying access test constant fakepost still show self "post" object. there way achieve this?
current:
irb(main):004:0> fakepost::test
=> ["post", "test1"]
but want return result when access constant through post not vi fakepost.
expected:
irb(main):004:0> fakepost::test
=> ["fakepost", "test1"]
the problem code test = ["#{self.name}", "test1"] interpreted once, when post class instantiated. after fixed ["post", "test1"].
off top of head can't think of way of making work constant, if replace class method works fine:
class post def self.test [self.name, "test1"] end end class fakepost < post end post.test #=> ["post", "test1"] fakepost.test #=> ["fakepost", "test1"] the reason works code inside class method interpreted @ run time (i.e. when call method), rather when class interpreted. timeline both cases follows:
with test constant:
- post class instantiated , interpreted line line.
self.nameinterpreted , returns'post',selfpostclass.post::testset irrevocably["post", "test1"]fakepostclass instantiated , inheritspost, including already-instantiatedtestconstant of["post", "test1"]fakepost::test == post::test == ["post", "test1"] #=> true
with test class method:
- post class instantiated , interpreted line line.
- post class method
testadded (but not interpreted yet). fakepostclass instantiated , inheritstestclass methodpost. still hasn't been interpreted yet.- when run
post.testorfakepost.testmethod interpreted.selfeitherpostorfakepostdepending on class calledtestmethod.
Comments
Post a Comment