How can I fix an inherited hook in a ruby?

A simple example.

class Base def self.inherited(child) p 'Base.inherited' end end class User < Base p 'User' end 

It gives me

 "Base.inherited" "User" 

This works fine, but how can I fix the inherited base class binding?

Say I want my result to be

 "Base.inherited" "Something inherited" "User" 

and so far my User class inherits the base.

Any ideas, workarounds?

Thanks!


Updating the question will be more specific.

I need to run some code exactly when the User class inherits the database without changing the User class.

Say I have a base class with a specific inherited method. For one thing, I don’t know which other classes inherit Base. On the other hand, I cannot change the original inherited method of the base class.

So how can I fix this method?

Thanks!

+4
source share
2 answers
 module Foo def self.included(child) p "Something inherited" end end class Base def self.inherited(child) p 'Base.inherited' end end class User < Base include Foo p 'User' end # >> "Base.inherited" # >> "Something inherited" # >> "User" 
+4
source

Found the answer.

In this case, the whole chain works. For some reason, I thought this worked with common methods, but not ruby ​​callbacks.

 class Base def self.inherited(child) p 'Base.inherited' end end Base.class_eval do class << self alias_method :chained_inherited, :inherited def inherited(child) chained_inherited(child) p 'Inherited' end end end class User < Base p 'User' end # => "Base.inherited" # => "Inherited" # => "User" 
+1
source

Source: https://habr.com/ru/post/1487132/


All Articles