Get child constant in parent method - Ruby Get child constant in parent method - Ruby ruby ruby

Get child constant in parent method - Ruby


EDIT: this answer is correct, although Wayne's is the more ruby-ish way to approach the problem.

Yes it is.

Your implementation will not work, because the parent tries to resolve EWOK locally. Parent doesn't have EWOK defined. However, you can tell Ruby to look specifically at the class of the actual instance the method was called on, to get EWOK.

this will work:

class Parent  def go    self.class::EWOK  endendclass Child < Parent  EWOK = "Ewoks Rule"endclass Child2 < Parent  EWOK = "Ewoks are ok, I guess"endbob = Child.newbob.go  # => "Ewoks Rule"joe = Child2.newjoe.go  # => "Ewoks are ok, I guess"

what's going on here:in Parent's 'go', "self" will refer to the instance of the object that 'go' is actually being called on. i.e., bob (a Child), or joe (a Child2). self.class gets the actual class of that instance - Child in the case of bob, or Child2 in the case of joe. then, self.class::EWOK will retrieve EWOK from the correct class.


For a parent class to have access to a constant defined in a child class, wrap that constant in a method. Then the normal inheritance rules apply:

class Parent  def ewok    "Ewoks are lame"  endendclass Child < Parent  def ewok    "Ewoks rule"  endendp Parent.new.ewok    # Ewoks are lamep Child.new.ewok     # Ewoks rule

If the constant is expensive to initialize (a large hash, for example), the define it in a constant, but access it via a method:

class Parent  EWOK = {    # Enormous hash...  }  def ewok    EWOK  endend