1

かなりの数のモデルで AASM を使用していますが、モデルを少し簡素化することを検討しています。私たちがやりたいことの 1 つは、すべての通知機能をモデルから Observer に移動することです。

したがって、次のことを考慮してください。

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 で active record dirty を使用して、state_was が開いていて現在閉じているかどうかを確認できます。

于 2010-02-10T09:50:24.310 に答える