入力アトリビュート
inputメソッドで期待されるすべてのアトリビュートを追加します。予期しない引数(inputアトリビュートとして定義されていないもの)はエラーになります。
使い方
inputsメソッドでinputアトリビュートにアクセスします。
ruby
class UsersService::Create < ApplicationService::Base
input :first_name, type: String
input :middle_name, type: String
input :last_name, type: String
internal :full_name, type: String
output :user, type: User
make :assign_full_name
make :create!
def assign_full_name
internals.full_name = [
inputs.first_name,
inputs.middle_name,
inputs.last_name
].join(" ")
end
def create!
outputs.user = User.create!(full_name: internals.full_name)
end
endオプション
詳細はオプションの使い方を参照してください。
ヘルパー
Servactoryはビルトインヘルパーを提供し、カスタムヘルパーもサポートしています。ヘルパーは特定のオプションに展開される省略記法です。
ヘルパーoptional
required: falseと同等です。
ruby
class UsersService::Create < ApplicationService::Base
input :first_name,
type: String
input :middle_name,
:optional,
type: String
input :last_name,
type: String
# ...
endカスタム
configurationのinput_option_helpersでカスタムヘルパーを追加します。ヘルパーは既存のオプションに基づいて作成できます。
mustの例
ruby
class PaymentsService::Create < ApplicationService::Base
input :invoice_numbers,
:must_be_6_characters,
type: Array,
consists_of: String
# ...
endprepareの例
ruby
class PaymentsService::Create < ApplicationService::Base
input :amount_cents,
:to_money,
as: :amount,
type: Integer
# ...
endメソッド
メソッドonly
onlyメソッドでinputsをフィルタリングします。指定されたアトリビュートを含むHashを返します。
ruby
outputs.full_name =
inputs.only(:first_name, :middle_name, :last_name)
.values
.compact
.join(" ")メソッドexcept
exceptメソッドでinputsをフィルタリングします。指定されたアトリビュートを除いたHashを返します。
ruby
outputs.full_name =
inputs.except(:gender)
.values
.compact
.join(" ")プレディケートメソッド
任意のinputアトリビュートをプレディケートメソッドとしてアクセスできます。
ruby
input :first_name, type: String
# ...
def something
return unless inputs.user? # instead of `inputs.user.present?`
# ...
end