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
  end
end

class Child < Parent
  EWOK = "Ewoks Rule"
end

class Child2 < Parent
  EWOK = "Ewoks are ok, I guess"
end

bob = Child.new
bob.go  # => "Ewoks Rule"

joe = Child2.new
joe.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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)