Ruby 如何预先编写类方法
这个问题直接关系到我们的利益。但是我试着把它分解成基本问题,我不想在另一个问题框中输入更多的文本。下面是: 我知道我可以通过扩展模块classmethods并通过模块#include hook包含它来包含classmethods。但是我能用prepend做同样的事情吗?以下是我的例子: Foo类:Ruby 如何预先编写类方法,ruby,Ruby,这个问题直接关系到我们的利益。但是我试着把它分解成基本问题,我不想在另一个问题框中输入更多的文本。下面是: 我知道我可以通过扩展模块classmethods并通过模块#include hook包含它来包含classmethods。但是我能用prepend做同样的事情吗?以下是我的例子: Foo类: class Foo def self.bar 'Base Bar!' end end 类扩展: module Extensions module ClassMethods
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
当我启动脚本时,我不会得到
扩展条代码>像我期望的那样,但更像是基本条代码>。要正常工作,我需要更改什么?问题是,即使您正在准备模块,ClassMethods
仍在extend
中。您可以这样做以获得您想要的:
module Extensions
module ClassMethods
def bar
'Extended Bar!'
end
end
def self.prepended(base)
class << base
prepend ClassMethods
end
end
end
模块扩展
模块类方法
def棒
“延长杆!”
结束
结束
def自我预装(基本)
类更简单的版本:
module Extensions
def bar
'Extended Bar!'
end
end
Foo.singleton_class.prepend Extensions
很不错的!谢谢。显然我不知道extend做什么。
module Extensions
def bar
'Extended Bar!'
end
end
Foo.singleton_class.prepend Extensions