2

私は現在、基本的に次のことを行っているクラスに取り組んでいます。

  • モデルが作成される
  • データをフェッチします (イベント「get_things!」)
    • 例外が発生した場合、状態は「失敗」になるはずです
    • 成功した場合、状態は「終了」する必要があります

私は次のように実装しようとします:

class Fetcher < ActiveRecord::Base
  include AASM

  aasm do
    state :created, initial: true
    state :success, :failed

    event :succeed do
      transitions from: :created, to: :success
    end

    event :fail do
      transitions from: :created, to: :failed
    end
  end

  def read_things!(throw_exception = false)
    begin
      raise RuntimeError.new("RAISED EXCEPTION") if throw_exception
      self.content = open("https://example.com?asd=324").read
      self.succeed!
    rescue => e
      self.fail!
    end
  end
end

a = Fetcher.new
a.read_things!(throw_exception = true)
=> state should be failed

a = Fetcher.new
a.read_things!(throw_exception = false)
=> state should be succeess

それは機能しますが、どういうわけか本当にうまくいかないようです...

readmeに記載されているエラー処理のようなものを好むでしょう

event :read_things do
  before do
    self.content = open("https://example.com?asd=324").read
    self.succeed!
  end
  error do |e|
    self.fail!
  end
  transitions :from => :created, :to => :success
end

しかし、これが本当にベストプラクティスであるかどうかはわかりませんか?

また、多くのイベントがあり、上記のエラー処理が上記のように動作する必要があり、error_on_all_events を使用できることがわかりましたが、それに関するドキュメントは見つかりませんでしたか?

何かご意見は?ありがとう!

編集:混乱を避けるためにいくつかの小さな部分を変更しました。

4

1 に答える 1