Ruby 延迟模块#包括回调?
是否有一种定义模块回调的方法类似于,但在接收器定义结束后调用 例如,为了能够访问包含后定义的接收方方法:Ruby 延迟模块#包括回调?,ruby,Ruby,是否有一种定义模块回调的方法类似于,但在接收器定义结束后调用 例如,为了能够访问包含后定义的接收方方法: module A def self.included(base) if base.respond_to? :foo puts ":foo is defined in #{base}" else puts ":foo is not defined in #{base}" end end end class B include A
module A
def self.included(base)
if base.respond_to? :foo
puts ":foo is defined in #{base}"
else
puts ":foo is not defined in #{base}"
end
end
end
class B
include A
def self.foo ; end
end
# :foo is not defined in B
可以在接收器定义的末尾包含模块,但感觉不太习惯:
class C
def self.foo ; end
include A
end
# :foo is defined in C
主要的区别(唯一的区别?)是,如果类混合了来自类中模块的方法,那么模块的方法将覆盖类
C
的方法,并被类B
的方法覆盖。是的,但是有办法避免这种行为吗?比如,当B到达类定义的末尾时,B调用了一个after_defined
hook。似乎没有比在末尾编写include更干净的方法了。您是否需要访问included
hook中的类定义,或者您只是希望模块方法优先于类的方法?如果是后者,你可以试试prepend
:我不知道它是否能给你买点什么,但你可以写class B;终止B.包括一个
。