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:

  1. post class instantiated , interpreted line line.
  2. self.name interpreted , returns 'post', self post class.
  3. post::test set irrevocably ["post", "test1"]
  4. fakepost class instantiated , inherits post, including already-instantiated test constant of ["post", "test1"]
  5. fakepost::test == post::test == ["post", "test1"] #=> true

with test class method:

  1. post class instantiated , interpreted line line.
  2. post class method test added (but not interpreted yet).
  3. fakepost class instantiated , inherits test class method post. still hasn't been interpreted yet.
  4. when run post.test or fakepost.test method interpreted. self either post or fakepost depending on class called test method.

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -