如何添加类方法 [英] How to prepend classmethods
问题描述
这个问题直接与这个问题有关.但我试图将其分解为基本问题,我不想在另一个问题框中输入更多文本.所以这里是:
This question directly relates to this one. But I tried to break it down to the base problem and I didn't want to enter even more text into the other question box. So here goes:
我知道我可以通过扩展模块 ClassMethods 并通过 Module#include 钩子包含它来包含类方法.但是我可以用 prepend 做同样的事情吗?这是我的例子:
I know that I can include classmethods by extending the module ClassMethods and including it via the Module#include hook. But can I do the same with prepend? Here is my example:
Foo 类:
class Foo
def self.bar
'Base Bar!'
end
end
类扩展:
module Extensions
module ClassMethods
def bar
'Extended Bar!'
end
end
def self.prepended(base)
base.extend(ClassMethods)
end
end
# prepend the extension
Foo.send(:prepend, Extensions)
FooE 类:
require './Foo'
class FooE < Foo
end
和一个简单的启动脚本:
and a simple startscript:
require 'pry'
require './FooE'
require './Extensions'
puts FooE.bar
当我启动脚本时,我得到的不是 Extended Bar!
,而是 Base Bar!
.我需要更改什么才能正常工作?
When I start the script I don't get Extended Bar!
like I expect but rather Base Bar!
. What do I need to change in order to work properly?
推荐答案
问题是,即使你预先准备了模块,ClassMethods
仍然被 extend
edin. 你可以这样做来得到你想要的:
The problem is that even though you're prepending the module, ClassMethods
is still getting extend
ed in. You could do this to get what you want:
module Extensions
module ClassMethods
def bar
'Extended Bar!'
end
end
def self.prepended(base)
class << base
prepend ClassMethods
end
end
end
请注意,Extensions
本身既可以放在 Foo
中,也可以包含在其中.重要的部分是在 ClassMethods
前面加上.
Note that Extensions
itself could be either prepended or included in Foo
. The important part is prepending ClassMethods
.
这篇关于如何添加类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!