简体   繁体   中英

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. 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. I'd rather not have to call super_duper_class_method in all the derived classes, but just specify the option instead.

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).

I suggest that you pass the method name as a symbol, and in the SuperDuperClass, call send on self to call the derived method.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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