How to dynamically alter inheritance in Ruby

后端 未结 7 1379
粉色の甜心
粉色の甜心 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 11:45

    Perhaps you are looking for this

    Child = Class.new Parent do
      def foo
        "foo"
      end
    end
    
    Child.ancestors   # => [Child, Parent, Object, Kernel]
    Child.new.bar     # => "bar"
    Child.new.foo     # => "foo"
    

    Since parent is an argument to Class.new, you can swap it out with other classes.

    I've used this technique before when writing certain kinds of tests. But I have difficulty thinking of many good excuses to do such a thing.


    I suspect what you really want is a module.

    class Agent
      def self.hook_up(calling_class, desired_parent_class)
        calling_class.send :include , desired_parent_class
      end
    end
    
    module Parent
      def bar
        "bar"
      end
    end
    
    class Child
      def foo
        "foo"
      end
    
      Agent.hook_up(self, Parent)
    end
    
    Child.ancestors   # => [Child, Parent, Object, Kernel]
    Child.new.bar     # => "bar"
    Child.new.foo     # => "foo"
    

    Though, of course, there is no need for the Agent at all

    module Parent
      def bar
        "bar"
      end
    end
    
    class Child
      def foo
        "foo"
      end
    
      include Parent
    end
    
    Child.ancestors   # => [Child, Parent, Object, Kernel]
    Child.new.bar     # => "bar"
    Child.new.foo     # => "foo"
    

提交回复
热议问题