如何构建 ToyStore 模型的观察者?
给定一个模型:
class User
include Toy::Store
attribute :name
end
我可以使用 ActiveModel::Observer 来构建观察者吗?我删除了 ActiveRecord 框架,因为我没有在 Rails 应用程序中使用它。
添加像这样的观察者:
class UserObserver < ActiveModel::Observer
def after_save(model)
puts "Hello!"
end
end
似乎不起作用。在应用程序配置中包含观察者不起作用,因为 ActiveRecord 框架已被删除。
Given a model:
class User
include Toy::Store
attribute :name
end
Can I use ActiveModel::Observer
to build an observer? I remove the ActiveRecord framework, as I am not using it in my Rails app.
Adding an observer like:
class UserObserver < ActiveModel::Observer
def after_save(model)
puts "Hello!"
end
end
does not seem to work. Including the observer in the application configuration does not work, because the ActiveRecord framework is removed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也想将观察者与 Toy::Store 一起使用。事实证明,在 Rails 中可观察到的普通对象生命周期事件(例如创建、保存、更新和删除)由于 ActiveRecord 的存在而变得可观察到。 Toy Store 对象是 ActiveModel 对象,并且没有相同的钩子。我在 为什么玩具店不与观察者合作。
但是,好消息是,仍然可以在玩具店中使用观察者,这取决于您来实现它们。我还发表了一篇关于How将观察者与 Toy::Store 一起使用
,但要点是:您的玩具对象(在本例中为
User
)必须包含ActiveModel::Observing
,并且必须在适合的情况下触发该事件该模型:I also wanted to use Observers with Toy::Store too. It turns out that the normal object lifecycle events, like create, save, update, and delete that are observable in Rails are observable because of ActiveRecord. Toy Store objects are ActiveModel objects and don't have the same hooks. I did a deep dive on the subject in a blog post on Why Toy Store Doesn't Work With Observers.
But, good news, it's still possible to use observers with toy store, it's just up to you to implement them. I also did a blog post on How to Use Observers With Toy::Store
, but here's the gist of it: your Toy Object, in this case
User
, must includeActiveModel::Observing
and must fire the event when it's appropriate for that model:您只能观察 ActiveModel 后代。它们不一定是 ActiveRecord 对象,正如您可以在 Yehuda Katz 的文章中读到的那样:
ActiveModel 使任何 ruby 对象都像 ActiveRecord
You can only observe ActiveModel descendants. They don't have to be ActiveRecord objects though as you can read in Yehuda Katz's article:
ActiveModel makes any ruby object feel like ActiveRecord