[英]How to overwrite eigenclass method in ruby?
我有一個模塊
module A
class << self
def is_okay?; false; end
end
end
我需要覆蓋is_okay?
另一個模塊中的方法。 模塊B
以這種方式包含在A
中
A.send(:include, B)
我已經試過了
module B
class << self
def is_okay?; true; end
end
end
然后
module B
def self.is_okay?; true; end
end
但這沒用。 我該如何實現?
這可能會或可能不會在您的情況下起作用:
module B
def is_okay?
true
end
end
module A
class << self
prepend B
def is_okay?
false
end
end
end
prepend
類似於include
,但前級插入本身,在祖先鏈的“底部”。
編輯:
由於您在下面的評論中做了澄清(我建議您澄清原始問題),因此可以將別名與其他任何方法相同。
module A
class << self
alias original_is_okay? is_okay?
def is_okay?
true
end
end
end
這將允許“覆蓋它,無論您是否有權訪問它”。
考慮以下。
module B
def bi
"hello from bi"
end
def self.bm
"hello from bm"
end
end
B.instance_methods(false)
#=> [:bi]
B.methods(false)
#=> [:bm]
請注意,使用self.
定義模塊方法(此處為bm
) self.
與在模塊的singleton類上定義實例方法相同。
現在創建一個包含B
的模塊A
module A
def self.am
"hello from am"
end
end
A.methods(false)
#=> [:am]
A.include B
A.instance_methods.include?(:bi)
#=> true
A.methods.include?(:bm)
#=> false
不出所料, bi
現在是A
的實例方法。 include
但不考慮模塊方法,這里B::bm
。 有什么方法可以使模塊方法B::m
成為A
的模塊方法? 答案是不”。 實際上,我們想要
A.singleton_class.include B.singleton_class
但這不起作用,因為B.singleton_class
是一個類。
Module#include並未明確模塊(可能是類)是否可以包含類。 嘗試一下,但是,您將看到以下引發的異常:
TypeError (wrong argument type Class (expected Module))
如果模塊M
模塊方法不可用於另一個包含M
的模塊,則模塊是否有理由使用模塊方法? 是的,提供方法庫! 一個示例是Math模塊。 該模塊包含許多模塊方法,而沒有實例方法。 因此,使用這些方法時,將在其接收者Math
上調用這些方法。 例如,
Math.sin(x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.