在Ruby中,如何实现全局行为?

发布于 2024-08-31 11:04:04 字数 676 浏览 9 评论 0原文

我想实现工作区的概念。这是一个全局概念 - 所有其他代码都将与此工作区的一个实例交互。工作区将负责维护当前的系统状态(即与系统模型交互、保留系统状态等)

那么我的工作区的最佳设计策略是什么,记住这必须是可测试的(现在使用 RSpec,但是很乐意寻找替代方案)。

阅读了一些开源项目后,我发现了 3 种策略。我无法将其中任何一个视为“最佳实践”。

它们是:

  1. 包含singleton类。但是这有多可测试呢? Workspace 的全局状态在测试之间会发生变化吗?
  2. 将所有行为实现为类方法。您如何测试这一点?
  3. 将所有行为实现为模块方法。对此完全不确定!

哪个最好?或者还有别的办法吗?

谢谢, Gordon

编辑

当我开始在所有代码中包含“单例”模块时,我意识到我的代码与各地的这些全局实例的引用是多么紧密地耦合。

因此,我开始完全删除它们并传递对全局实例的引用。但现在我正沿着 IOC 的路线前进——通过我的构造函数向下传递依赖项。

这在 Ruby 中是个好主意吗?或者我错过了什么?

顺便说一句,您可能已经知道我是 Ruby 新手!

I want to implement the concept of a Workspace. This is a global concept - all other code will interact with one instance of this Workspace. The Workspace will be responsible for maintaining the current system state (i.e. interacting with the system model, persisting the system state etc)

So what's the best design strategy for my Workspace, bearing in mind this will have to be testable (using RSpec now, but happy to look at alternatives).

Having read thru some open source projects out there and I've seen 3 strategies. None of which I can identify as "the best practice".

They are:

  1. Include the singleton class. But how testable is this? Will the global state of Workspace change between tests?
  2. Implemented all behaviour as class methods. Again how do you test this?
  3. Implemented all behaviour as module methods. Not sure about this one at all!

Which is best? Or is there another way?

Thanks,
Gordon

Edit

As I started including the 'singleton' module in all my code and I realised just how tightly coupled I had made my code, with references to these global instances all over the place.

So I've started to remove them entirely and pass references to the global instances instead. But now I'm heading down the route of IOC - passing dependencies down through my constructers.

Is this a good idea in Ruby? Or am I missing something?

BTW you may have gathered I'm new to Ruby!

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

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

发布评论

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

评论(2

坦然微笑 2024-09-07 11:04:05

也许标准库中的 Singleton 模块 会有用?如果您将此模块包含在您的类中,则只能创建它的一个实例。然后,您可以使用实例变量来管理工作区的状态等。

如果这就是您所说的“包含单例类”的意思,那么我很抱歉,但是术语“单例”在 Ruby 领域中经常被使用,通常在此上下文中。

Maybe the Singleton module from the standard library would be useful? If you include this module in your class, only one instance of it can be created. You then can use instance variables for managing the state of your workspace etc.

If this was what you meant by "Include the singleton class", then I'm sorry, but the term "singleton" gets thrown around quite a bit in Ruby land, usually in this context.

蓝咒 2024-09-07 11:04:05

从性能角度来看,单例方法是最佳选择。为了在测试期间不改变它,您可以使用模型。

The singleton approach is best choice, performance wise. For it not to change during tests you can use a mock up.

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