Skip to content

アクションの使い方

サービス内のアクションは、メソッドを順次呼び出すものです。 サービスのメソッドはmakeメソッドを使用して呼び出します。

最小構成

最小構成では、makeによるメソッド呼び出しは任意です。 代わりにcallメソッドを使用できます。

ruby
class PostsService::Create < ApplicationService::Base
  def call
    # something
  end
end

複数のメソッド

ruby
class PostsService::Create < ApplicationService::Base
  # ...

  make :assign_api_model
  make :perform_api_request
  make :process_result

  def assign_api_model
    internals.api_model = APIModel.new(...)
  end

  def perform_api_request
    internals.response = APIClient.resource.create(internals.api_model)
  end

  def process_result
    ARModel.create!(internals.response)
  end
end

オプション

詳細はオプションセクションを参照してください。

複数のアクションのグループ

詳細はグルーピングセクションを参照してください。

makeのエイリアス

action_aliases設定でmakeメソッドの代替を追加します。

ruby
configuration do
  action_aliases %i[execute]
end

execute :something

def something
  # ...
end

makeのカスタマイズ

action_shortcuts設定でよく使うメソッド名のプレフィックスを追加します。 メソッド名の長さは変わりませんが、makeの行が短く読みやすくなります。

シンプルモード

シンプルモードでは、値はシンボルの配列として渡します。

ruby
configuration do
  action_shortcuts %i[assign perform]
end
ruby
class CMSService::API::Posts::Create < CMSService::API::Base
  # ...

  assign :model

  perform :request

  private

  def assign_model
    # Build model for API request
  end

  def perform_request
    # Perform API request
  end

  # ...
end

アドバンスドモード 2.14.0以降

アドバンスドモードでは、値はハッシュとして渡します。

ruby
configuration do
  action_shortcuts(
    %i[assign],
    {
      restrict: {           # replacement for make
      prefix: :create,      # method name prefix
      suffix: :restriction  # method name suffix
      }
    }
  )
end
ruby
class PaymentsService::Restrictions::Create < ApplicationService::Base
  input :payment, type: Payment

  # The exclamation mark will be moved to the end of the method name
  restrict :payment!

  private

  def create_payment_restriction!
    inputs.payment.restrictions.create!(
      reason: "Suspicion of fraud"
    )
  end
end