用事件挂钩观察者
我们在很多模型中使用 AASM,但我们正在考虑稍微简化模型。我们想做的一件事是将所有通知内容从模型中移出并放入观察者中。
所以考虑一下:
class ClarificationRequest < ActiveRecord::Base
include AASM
aasm_initial_state :open
# States
aasm_state :open
aasm_state :closed
# Events
aasm_event :close, :after => :notify_closed do transitions :to => :closed, :from => [:open,:replied], :guard => :can_close? end
end
我已经尝试过这个,但没有运气:
class ClarificationRequestObserver < ActiveRecord::Observer
observe :clarification_request
def after_close
puts '############### message from observer!!!!!'
end
end
如何将 :notify_close 移动到观察者?
谢谢!
.卡里姆
We are using AASM in quite a few of our models, but we're looking at simplifying a bit the models. One of the things we'd like to do is to move all the Notification stuff out of the models and into Observers.
So considering:
class ClarificationRequest < ActiveRecord::Base
include AASM
aasm_initial_state :open
# States
aasm_state :open
aasm_state :closed
# Events
aasm_event :close, :after => :notify_closed do transitions :to => :closed, :from => [:open,:replied], :guard => :can_close? end
end
I've tried this, but with no luck:
class ClarificationRequestObserver < ActiveRecord::Observer
observe :clarification_request
def after_close
puts '############### message from observer!!!!!'
end
end
How can I move the :notify_closed to an Observer?
Thx!
.Karim
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我之前在github上回复过你的评论,我在这里重复一下,以防万一
I've reply to your comment on github before, I'll repeat it here, just in case
说实话,我觉得你过得很好。对于这样的事情使用 AASM 钩子是有意义的。这样您就知道它已转换正常,然后您发送通知。
您可以查看在 before_update 中使用活动记录 dirty 来检查 state_ 是否已打开且现在已关闭。
To be honest I think how you had it is fine. It makes sense to use the AASM hooks for stuff like this. This way you know it's transitioned OK and then you send the notification.
You could look at using active record dirty in a before_update to check if the state_was open and now closed.
我会做这样的事情:
您还应该将观察者包含在 config/environment.rb 的 config.active_record.observers 列表中
原因是观察者应该观察一个对象。通过主动通知模型中的观察者(并与之交互),您假设有一个可用的观察者,但我不认为您可以安全地做到这一点(看看观察者通常在现实世界中的行为方式)。观察者是否对事件感兴趣应该由观察者决定。
I would do something like this:
You should also include the observer in the
config.active_record.observers
list in config/environment.rbThe reason for that is that an observer should observe an object. By actively notifying (and interacting with) the observer from the model you assume that there is one available, which I don't believe that you safely can do (seeing how observers usually behave in the real world). It should be up to the observer whether it is interested of the event or not.