简体   繁体   English

Ruby从基类访问派生类“类方法”

[英]Ruby access derived class “class methods” from base class

I have a base class in Ruby that has a class method which it has inherited. 我在Ruby中有一个基类,它有一个继承的类方法。 I would like to call this method in the base class, but pass it an option which is specified by the derived class, like so: 我想在基类中调用此方法,但是传递一个由派生类指定的选项,如下所示:

class Base < SuperDuperClass
  super_duper_class_method :option => my_option_value

  def self.my_option_value
    raise "Method my_option_value must be overridden by all subclasses"
  end
end

class Derived < Base
  def self.my_option_value
    "My Derived Option Value"
  end
end

However, this isn't working. 但是,这不起作用。 I believe it's because the top-level code in the base class is executed before the top-level code in the derived class, so the derived method is not defined when super_duper_class_method is called. 我相信这是因为基类中的顶级代码在派生类中的顶级代码之前执行,因此在调用super_duper_class_method时未定义派生方法。 I'd rather not have to call super_duper_class_method in all the derived classes, but just specify the option instead. 我宁愿不必在所有派生类中调用super_duper_class_method,而只需指定选项。

Any ideas? 有任何想法吗?

You weren't specific when you said it wasn't working. 当你说它不起作用时,你并不具体。 I believe you will get an exception raised when the Base class is defined, (rather than when my_option_value is called). 我相信在定义Base类时会引发异常(而不是在调用my_option_value时)。

I suggest that you pass the method name as a symbol, and in the SuperDuperClass, call send on self to call the derived method. 我建议您将方法名称作为符号传递,并在SuperDuperClass中,调用send on self来调用派生方法。

class SuperDuperMethod
  def self.some_code
    self.class.__send__(options[:option])
  end
...

Just to close this off, my solution is to call super_duper_class_method in the subclasses. 只是为了关闭它,我的解决方案是在子类中调用super_duper_class_method This is what I was trying to avoid, but in this situation, I don't think it's possible to get what I was going for without some pretty wild metaprogramming. 这是我试图避免的,但在这种情况下,我认为如果没有一些非常狂野的元编程,我就不可能得到我想要的东西。

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

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