如何构建 ToyStore 模型的观察者?

发布于 2024-11-05 08:50:17 字数 382 浏览 4 评论 0原文

给定一个模型:

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 技术交流群。

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

发布评论

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

评论(2

像极了他 2024-11-12 08:50:17

我也想将观察者与 Toy::Store 一起使用。事实证明,在 Rails 中可观察到的普通对象生命周期事件(例如创建、保存、更新和删除)由于 ActiveRecord 的存在而变得可观察到。 Toy Store 对象是 ActiveModel 对象,并且没有相同的钩子。我在 为什么玩具店不与观察者合作

但是,好消息是,仍然可以在玩具店中使用观察者,这取决于您来实现它们。我还发表了一篇关于How将观察者与 Toy::Store 一起使用
,但要点是:您的玩具对象(在本例中为 User)必须包含 ActiveModel::Observing,并且必须在适合的情况下触发该事件该模型:

class User
  include Toy::Store
  attribute :name
  after_save :notify_observers_save_occured

  private

  def notify_observers_save_occured
    self.class.notify_observers(:after_save, self)
  end

end

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 include ActiveModel::Observing and must fire the event when it's appropriate for that model:

class User
  include Toy::Store
  attribute :name
  after_save :notify_observers_save_occured

  private

  def notify_observers_save_occured
    self.class.notify_observers(:after_save, self)
  end

end
桃气十足 2024-11-12 08:50:17

您只能观察 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

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