简体   繁体   English

如何在运行时在特定类的前面?

[英]How to prepend specific class at run time?

Is it possible to use prepend for instantiated classes at run time? 在运行时是否可以对实例化的类使用prepend Like for example, I need prepend specific class based of value of passed params to initialize method.. 例如,我需要根据传递的参数的值在特定类之前添加前缀以初始化方法。

ex (if prepend is allowed to be called in initialize) : ex(如果允许在初始化中调用prepend):

def initialize(param)
    prepend TestB if param == 2
    prepend TestC if param == 3
end

but of course, this will lead into error: 但这当然会导致错误:

NoMethodError: undefined method `prepend' for .. etc

How would I achieve this? 我将如何实现? I need to override some methods in a clean way, while instantiating the same class. 在实例化同一类时,我需要以一种干净的方式重写某些方法。

prepend is a method belonging to Module , so it cannot be invoked on instances of a class (which is where you are inside the initialize method). prepend是属于Module的方法,因此无法在类的实例(在initialize方法内的位置)上调用它。 If you want to, you could use extend (a method belonging to Object ) to mix in different method implementations into the instance of your class. 如果愿意,可以使用extend (属于Object的方法)将不同的方法实现混入类的实例中。

Personally I would consider this to be a kind of Control Couple and rather try and avoid it. 就我个人而言,我认为这是一种控制偶 ,而是尽量避免。 Depending on your concrete situation, a factory or adapter pattern might be more appropriate. 根据您的具体情况,工厂或适配器模式可能更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM