Search code examples
rubyinheritanceclass-method

Ruby Inheritance and overwriting class method


I have set up two classes as shown below

class Parent

  def self.inherited(child)
    child.custom_class_method
  end

  def self.custom_class_method
    raise "You haven't implemented me yet!"
  end
end

class Child < Parent

  def self.custom_class_method
    "hello world"
  end
end

It seems that when the inheritence Child < Parent is evaluated, it calls self.inherited, which in turn raises the Parent's version of self.custom_class_method instead of the Child's. This is a problem because instead of getting an expected "hello world" I get an error raised saying "You haven't implemented me yet!"

Does Child's self.custom_class_method not get evaluated until after Parent's self.inherited is finished evaluating? And if so is there perhaps a work around this? Should I just not put a raise check on the Parent class?


Solution

  • I think this should clarify:

    class Parent
      def self.inherited(child)
        puts "Inherited"
      end
    end
    
    class Child < Parent
      puts "Starting to define methods"
      def self.stuff; end
    end
    

    Output makes it clear that .inherited gets called the moment you open the new class, not when you close it. Thus, as you guessed, Child.custom_class_method does not exist at the point when you are trying to call it - all .inherited sees is a blank slate.

    (As to how to get around it... I can't say without more insight into what you are trying to do, unfortunately.)