用事件挂钩观察员

时间:2010-02-10 05:25:41

标签: ruby-on-rails aasm

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

THX!

.Karim

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

说实话,我觉得你有这样的感觉很好。对这样的东西使用AASM钩子是有意义的。通过这种方式,您可以确定已转换为OK,然后发送通知。

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

答案 2 :(得分: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 / environment.rb

中的config.active_record.observers列表中

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