1

我们在很多模型中都使用了 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_closed 移动到观察者?

谢谢!

.卡里姆

4

3 回答 3

1

之前在github上回复过你的评论,这里再重复一遍,以防万一

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

    # Notify Observer
    def notify_closed
     notify :close # this will trigger after_close method call in ClarificationRequestObserver
     # notify :closed # this will trigger after_closed method call in ClarificationRequestObserver
     # notify :whatever # this will trigger after_whatever method call in ClarificationRequestObserver
    end
end
于 2010-02-13T17:13:04.803 回答
0

我会做这样的事情:

class ClarificationRequest < ActiveRecord::Base
  include AASM

  aasm_initial_state :open

  # States
  aasm_state :open
  aasm_state :closed, :enter => :do_close

  # Events
  aasm_event :close do transitions :to => :closed, :from => [:open,:replied], :guard => :can_close? end

  def recently_closed?
    @recently_closed
  end 
protected
  def do_close
    @recently_closed = true
  end

end


class ClarificationRequestObserver < ActiveRecord::Observer
  observe :clarification_request

  def after_save(clarification_request)
    puts '############### message from observer!!!!!' if clarification_request.recently_closed?
  end
end

您还应该config.active_record.observers在 config/environment.rb 的列表中包含观察者

原因是观察者应该观察一个物体。通过主动通知模型中的观察者(并与之交互),您假设有一个可用的模型,我不相信您可以安全地做到这一点(看看观察者在现实世界中通常的行为方式)。是否对事件感兴趣应该由观察者决定。

于 2010-02-13T17:39:38.987 回答
0

老实说,我认为你的表现很好。将 AASM 钩子用于此类事情是有意义的。这样你就知道它已经转换好了,然后你发送通知。

您可以查看在 before_update 中使用活动记录脏来检查 state_was 是否打开并且现在关闭。

于 2010-02-10T09:50:24.310 回答