[英]How to call super on dynamicly defined methods in sub-classes in Ruby?
我有一個元編程方案,它涉及到我不確定如何解決的Ruby的一些較優功能。
每個人都可以輕松編寫以下示例的程序來執行其應做的事情,但是我需要在超類和派生子類中動態定義方法。
在該示例中,基類具有動態定義的方法:foo,當然,它公開給子類B。但是,當我在子類B的實例上調用:foo時,我在動態定義的方法中檢測到我似乎無法將方法從B類實例傳遞到A類實例,這就是我想要的。
有點像紅寶石一樣在子類中定義方法,但是無論如何,這就是我要解決的問題。
有什么線索嗎?
class A
def self.some_method method,*_params
puts "#{name}: defining #{method}"
define_method method do |*args|
puts "#{self.class.name}: called #{method}"
super *args unless self.class.instance_methods(false).include?(method)
end
end
end
class B < A
end
A.some_method :foo
B.new.foo
輸出量
A: defining foo
B: called foo
NoMethodError: super: no superclass method `foo' for #<B:0x007f9eab85bfa0>
我認為您的邏輯存在缺陷。
您可以為超類A
定義動態方法。 調用B.new.foo
在B
找不到任何方法,因此它繼承了繼承行。 它在A
找到foo
方法,因此使用該方法。
這意味着
super *args unless self.class.instance_methods(false).include?(method)
根本不需要。
按照我的看法,經典方法繼承就是您所需要的!
邏輯確實存在缺陷。 當然需要在何處訪問已定義方法的類,而super並不能幫助您。
以下是該問題的解決方案:
class A
def self.some_method method,*_params
puts "#{name}: defining #{method}"
define_method method do |*args|
puts "#{self.class.name}: called #{method}"
klass = self.class
klass = klass.superclass while !klass.instance_methods(false).include?(method)
# klass is now where the instance method is defined
# and you can now access its class variables etc.
puts "#{klass.name}: has method #{method}"
end
end
end
class B < A
end
A.some_method :foo
B.new.foo
輸出量
A: defining foo
B: called foo
A: has method foo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.