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.name
interpreted , returns'post'
,self
post
class.post::test
set irrevocably["post", "test1"]
fakepost
class instantiated , inheritspost
, including already-instantiatedtest
constant of["post", "test1"]
fakepost::test == post::test == ["post", "test1"] #=> true
with test
class method:
- post class instantiated , interpreted line line.
- post class method
test
added (but not interpreted yet). fakepost
class instantiated , inheritstest
class methodpost
. still hasn't been interpreted yet.- when run
post.test
orfakepost.test
method interpreted.self
eitherpost
orfakepost
depending on class calledtest
method.
Comments
Post a Comment