Servactoryの始め方
規約
- サービスは
Servactory::Baseを継承し、app/servicesに配置します。一般的な方法: プロジェクトの基底クラスとしてApplicationService::Baseを作成します。 - サービスは受け取るものではなく、実行する内容に基づいて命名します。動詞を使用してください。例:
UsersService::CreationではなくUsersService::Create。
バージョンサポート
| Ruby/Rails | 8.1 | 8.0 | 7.2 | 7.1 | 7.0 | 6.1 | 6.0 | 5.2 | 5.1 | 5.0 |
|---|---|---|---|---|---|---|---|---|---|---|
| 4.0 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
| 3.4 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| 3.3 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| 3.2 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| 3.1 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
インストール
Gemfileに以下を追加します:
ruby
gem "servactory"そして以下を実行します:
shell
bundle install準備
まず、継承用の基底クラスを準備します。
自動 2.5.0以降
ジェネレーターを実行します:
shell
bundle exec rails g servactory:install必要なファイルがすべて作成されます。
利用可能なすべてのオプションとジェネレーターについては、Railsジェネレーターを参照してください。
手動
ApplicationService::Exceptions
ruby
module ApplicationService
module Exceptions
class Input < Servactory::Exceptions::Input; end
class Output < Servactory::Exceptions::Output; end
class Internal < Servactory::Exceptions::Internal; end
class Failure < Servactory::Exceptions::Failure; end
end
endApplicationService::Result 2.5.0以降
ruby
module ApplicationService
class Result < Servactory::Result; end
endApplicationService::Base
ruby
module ApplicationService
class Base < Servactory::Base
configuration do
input_exception_class ApplicationService::Exceptions::Input
internal_exception_class ApplicationService::Exceptions::Internal
output_exception_class ApplicationService::Exceptions::Output
failure_class ApplicationService::Exceptions::Failure
result_class ApplicationService::Result
end
end
end最初のサービス
最初のサービスを作成します:
shell
bundle exec rails g servactory:service users_service/create first_name middle_name last_nameスペックファイルを生成します:
shell
bundle exec rails g servactory:rspec users_service/create first_name middle_name last_name