相当于 Rails 的 Django Signals?
在 Rails 中,我见过的最接近 Django 信号 的是 观察者。 它们的问题在于,它们仅限于触发与模型生命周期相关的硬编码事件的回调。
Django 信号可以在任何地方创建、在任何地方触发并在任何地方处理。 模型生命周期回调只是碰巧内置的常规信号,由 ORM 触发。
有谁知道 Rails 有类似的通用解决方案吗? 它可以是一些通用的 Ruby 库,不依赖于 Rails,这会更好。
编辑:观察者是最接近的东西,但它不是我正在寻找的东西。 这是一个一对多的解决方案。 任何人都可以收听,但只有原始对象可以发帖。 我想要一个声明信号的东西,任何人都可以触发它并处理它。 另外,我不喜欢 Ruby Observer 规定处理程序具有 #update 方法。 我希望能够传递具有适当签名的任何方法引用。
我可以使用 Ruby Observer 来实现我自己的此类代理,但我正在尝试了解是否有人已经这样做了。
In Rails, the closest I've seen to Django Signals are Observers. The problem with them is that they're restricted to triggering callbacks on hardcoded events related to a model's lifecycle.
Django signals can be created anywhere, triggered anywhere and handled anywhere. The model lifecycle callbacks are just regular signals that happen to come built-in and that are triggered by the ORM.
Does anyone know of a similarly general solution for Rails? It could be some generic Ruby library, not tied to Rails, which would be even better.
Edit: Observer is the closest thing, but it's not what I'm looking for. It's a one-to-many solution. Anyone can listen, but only the originating object can post. I'd like something where you declare a signal, and anyone can trigger it as well as handle it. Also, I don't like the fact that the Ruby Observer dictates that the handler have an #update method. I'd like to be able to pass any method reference with the appropriate signature.
I could use the Ruby Observer to implement my own such broker, but I'm trying to learn if someone already did it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许acts_as_state machine 会有所帮助。 大部分功能最近已融入 Rails Edge 中。
Perhaps acts_as_state machine will help. Most of this functionality has recently been baked into Rails edge.
我刚刚用它实现了一个 gem。 https://github.com/pkoch/django_signal/
I just implemented a gem with that. https://github.com/pkoch/django_signal/
红宝石‘耐看’是最合适的选择
https://github.com/jbarnette/watchable
它的语法对于 Django 来说非常熟悉(并且其他框架,如 Qt 等)。
Ruby gem 'watchable' is the most appropriate choice
https://github.com/jbarnette/watchable
It has a syntax that is very familiar to Django's (and other frameworks, like Qt and many others).
我认为比 Rails 的 Observer 更接近的是 标准 Ruby Observable 模块< /a>. 它允许您向对象添加观察者列表,然后该对象可以在发生更改时向观察者发送通知。
I think a closer equivalent than Rails' Observer is the standard Ruby Observable module. It lets you add a list of observers to an object and the object can then send notifications to the observers when it changes.
那么‘慧语’宝石呢? https://github.com/krisleech/wisper
What about the 'wisper' gem? https://github.com/krisleech/wisper