Question : Call a method on a child class when inherited in Ruby

Ruby has the cool little method "inherited" . . . All I want to do is whenever another class inherits from this parent class, I want to call a specific method on the child
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
#Parent class
    class TestScript
      def self.inherited(subclass)
          test = subclass.new()
 
          #This failed to i commented it out
          #test.send(:run)
#this throws an error
          test.run()
      end
    end
 
#Child class
class Example < TestScript
  
  def initialize(options={});end;
  
  def run()
    return "I get an error that says this method doesn't exist"
  end
  
end
Open in New Window Select All

Answer : Call a method on a child class when inherited in Ruby

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
class TestScript
  
      def TestScript.children
        @children ||= []
      end
  
      def self.inherited(subclass)
        super
      ensure
        children << subclass.new()
        children.last.run()
      end
      
end
Open in New Window Select All
Random Solutions  
 
programming4us programming4us