[英]Assert that Ruby module extends another module
I have two modules A & B, I am extending A into B in order to use the methods of A in B as class methods:我有两个模块 A 和 B,我将 A 扩展到 B 以便将 B 中的 A 的方法用作类方法:
module A
def foo
end
end
module B
extend A
end
B.Foo
I'd like to write a test to assert that module B Extends A. Currently Ruby does not implement an extends?我想写一个测试来断言模块 B 扩展了 A。目前 Ruby 没有实现扩展? method but I think that would be a great idea.方法,但我认为这将是一个好主意。 Is there anyway to assert that a module extends another module?无论如何断言一个模块扩展了另一个模块? I could use the responds_to?我可以使用 responds_to 吗? method but I'd have to loop over all of the methods in the extending module and that in my opinion is not a great design.方法,但我必须遍历扩展模块中的所有方法,我认为这不是一个很好的设计。 Thanks again, peace.再次感谢,平安。
I agree with @spickermann's comment that it doesn't seem like a useful test, that said:我同意@spickermann 的评论,即这似乎不是一个有用的测试,他说:
included_singleton_modules = B.singleton_class.included_modules #[A, Kernel]
assert(included_singleton_moduls.include? A)
Gives you what you want.给你你想要的。
class C
include M
end
essentially just "inserts" M
into the ancestry chain as the superclass of C
.本质上只是将M
作为C
的超类“插入”到祖先链中。 Or, more precisely, it creates an include class from M
, makes that include class the superclass of C
and the old superclass of C
the superclass of the include class.或者,更准确地说,它从M
创建一个包含类,使该包含类成为C
的超类,并使C
的旧超类成为包含类的超类。
Furthermore,此外,
class C
extend M
end
is essentially just the same as本质上是一样的
class << C
include M
end
ie it inserts M
into the the ancestry chain of the singleton class of C
.即它将M
插入到C
的单例类的祖先链中。
Since C
is an instance of its singleton class and M
is the superclass of the singleton class, C
is an instance of M
.由于C
是其单例类的实例,而M
是单例类的超类,因此C
是M
的实例。
What this means is that all you need to do is这意味着您需要做的就是
B.is_a?(A)
#=> true
However, as mentioned in other answers and comments, you don't really care that B
is an instance of A
.但是,正如其他答案和评论中提到的那样,您并不真正关心B
是A
的实例。 What you do care about is that when you call B.foo
, you get the behavior that you expect.你关心的是当你调用B.foo
时,你会得到你期望的行为。 So, assert that .所以,断言.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.