How to dynamically alter inheritance in Ruby

后端 未结 7 1359
粉色の甜心
粉色の甜心 2020-12-06 11:30

I would like to dynamically specify the parent class for a class in Ruby. Consider this code:

class Agent
  def self.hook_up(calling_class, desired_parent_c         


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-06 12:05

    I know this question is pretty old and already has some good answers. However I still miss a certain solution.

    If your intention is not to dynamically assign the superclass, but rather create a hook to execute some code on inheritance (XY Problem). There is a build-in way to do this.

    inherited(subclass)

    Callback invoked whenever a subclass of the current class is created.

    Example:

    class Foo
      def self.inherited(subclass)
        puts "New subclass: #{subclass}"
      end
    end
    
    class Bar < Foo
    end
    
    class Baz < Bar
    end
    

    produces:

    New subclass: Bar
    New subclass: Baz
    

    See: Class#inherited

    If your intention is to dynamically create classes, I'd recommend looking at the answer of Joshua Cheek.

提交回复
热议问题