Skip to content

アクションのグルーピング

stageメソッドで複数のメソッドを1つの実行グループにまとめます。

INFO

makepositionオプションはstage内でのみソートされます。

ruby
stage do
  make :create_user!
  make :create_blog_for_user!
  make :create_post_for_user_blog!
end

オプションonly_if

stage内のメソッド呼び出しの前にonly_if条件を確認します。

ruby
stage do
  only_if ->(context:) { Settings.features.preview.enabled }
  
  make :create_user!
  make :create_blog_for_user!
  make :create_post_for_user_blog!
end

オプションonly_unless

only_ifオプションの逆です。

ruby
stage do
  only_unless ->(context:) { Settings.features.preview.disabled }

  make :create_user!
  make :create_blog_for_user!
  make :create_post_for_user_blog!
end

オプションwrap_in

stage内のメソッドをラッパーで包みます。 例: RailsのActiveRecord::Base.transaction

ruby
stage do
  wrap_in ->(methods:, context:) { ActiveRecord::Base.transaction { methods.call } }
  
  make :create_user!
  make :create_blog_for_user!
  make :create_post_for_user_blog!
end

オプションrollback

グループ内のメソッドまたはwrap_inからの例外をrollbackメソッドで処理します。

ruby
stage do
  wrap_in ->(methods:, context:) { ActiveRecord::Base.transaction { methods.call } }
  rollback :clear_data_and_fail!
  
  make :create_user!
  make :create_blog_for_user!
  make :create_post_for_user_blog!
end

# ...

def clear_data_and_fail!(e)
  # ...

  fail!(message: "Failed to create data: #{e.message}")
end