断言红宝石模块扩展了另一个模块

发布于 2025-01-28 10:07:43 字数 258 浏览 3 评论 0原文

我有两个模块A& B,我将A扩展到B中,以便使用B中的A方法作为类方法:

module A
   def foo
   end 
end 

module B
   extend A
end 

B.Foo

我想编写一个测试以断言模块B扩展A。方法,但我认为这是一个好主意。无论如何,是否有声称一个模块扩展了另一个模块?我可以使用响应_to?方法但我必须循环循环扩展模块中的所有方法,我认为这不是一个很好的设计。再次感谢,和平。

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:

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? 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? 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清泪尽 2025-02-04 10:07:43

我同意 @Spickermann的评论,即这似乎不是一个有用的测试,也就是说:

included_singleton_modules = B.singleton_class.included_modules #[A, Kernel]
assert(included_singleton_moduls.include? A)

给您想要的东西。

I agree with @spickermann's comment that it doesn't seem like a useful test, that said:

included_singleton_modules = B.singleton_class.included_modules #[A, Kernel]
assert(included_singleton_moduls.include? A)

Gives you what you want.

咋地 2025-02-04 10:07:43
class C
  include M
end

从本质上讲,只是“插入” m作为c的超级阶级。或者,更确切地说,它创建一个来自m的class ,使得将其包括c的超类和的旧超级类别C包括类的超级类。

此外,

class C
  extend M
end

本质上与

class << C
  include M
end

singleton class c的祖先链中插入m

由于c是其Singleton类的实例,m是Singleton类的超级类,cm m c /代码>。

这意味着,您需要做的只是

B.is_a?(A)
#=> true

其他答案和评论中提到的,您 不关心b的实例。您的关心是,当您致电b.foo时,您会得到您期望的行为。因此,断言

class C
  include M
end

essentially just "inserts" M into the ancestry chain as the superclass of 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.

Furthermore,

class C
  extend M
end

is essentially just the same as

class << C
  include M
end

i.e. it inserts M into the the ancestry chain of the singleton class of 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.

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. What you do care about is that when you call B.foo, you get the behavior that you expect. So, assert that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文