Использование опций в атрибутах
Опция type input internal output
Опция валидации. Проверяет соответствие переданного значения указанному типу (классу) через is_a?.
Обязательна. Может содержать один или несколько классов.
class NotificationsService::Create < ApplicationService::Base
input :user, type: User
input :need_to_notify, type: [TrueClass, FalseClass]
# ...
endclass NotificationsService::Create < ApplicationService::Base
# ...
internal :inviter, type: User
# ...
endclass NotificationsService::Create < ApplicationService::Base
# ...
output :notification, type: Notification
# ...
endОпция required input
Опция валидации. Проверяет, что переданное значение не пустое, через present?.
По умолчанию true.
class UsersService::Create < ApplicationService::Base
input :first_name,
type: String
input :middle_name,
type: String,
required: false
input :last_name,
type: String
# ...
endОпция default input
Не является валидацией. Назначает значение, если оно не передано в сервис.
class UsersService::Create < ApplicationService::Base
# ...
input :middle_name,
type: String,
required: false,
default: "<unknown>"
# ...
endОпция as input
Не является валидацией. Указывает псевдоним атрибута для работы внутри сервиса. Исходное имя становится недоступным.
class NotificationsService::Create < ApplicationService::Base
input :user,
as: :recipient,
type: User
# ...
def create!
outputs.notification =
Notification.create!(recipient: inputs.recipient)
end
endОпция inclusion input internal (^2.2.0) output (^2.2.0)
INFO
Начиная с версии 2.12.0 эта опция является динамической.
Динамическая опция валидации. Проверяет, что переданное значение находится в указанном массиве, через include?.
class EventsService::Send < ApplicationService::Base
input :event_name,
type: String,
inclusion: %w[created rejected approved]
# ...
endclass EventsService::Send < ApplicationService::Base
# ...
internal :event_name,
type: String,
inclusion: %w[created rejected approved]
# ...
endclass EventsService::Send < ApplicationService::Base
# ...
output :event_name,
type: String,
inclusion: %w[created rejected approved]
# ...
endОпция consists_of input (^2.0.0) internal (^2.0.0) output (^2.0.0)
INFO
Начиная с версии 2.6.0 эта опция является динамической.
Динамическая опция валидации. Проверяет соответствие каждого значения в коллекции указанному типу (классу), включая вложенные значения, через is_a?.
Работает только с типами Array и Set. Добавьте собственный тип через конфигурацию collection_mode_class_names.
Необязательна. По умолчанию String.
input :ids,
type: Array,
consists_of: Stringinternal :ids,
type: Array,
consists_of: Stringoutput :ids,
type: Array,
consists_of: StringОпция schema input (^2.0.0) internal (^2.0.0) output (^2.0.0)
INFO
Начиная с версии 2.12.0 эта опция является динамической.
Динамическая опция валидации. Требует хеш, описывающий структуру значения атрибута.
Работает только с типом Hash. Добавьте собственный тип через конфигурацию hash_mode_class_names.
Необязательна. Если не указана, валидация пропускается. Значения по умолчанию нет.
input :payload,
type: Hash,
schema: {
request_id: { type: String, required: true },
user: {
type: Hash,
required: true,
first_name: { type: String, required: true },
middle_name: { type: String, required: false, default: "<unknown>" },
last_name: { type: String, required: true },
pass: {
type: Hash,
required: true,
series: { type: String, required: true },
number: { type: String, required: true }
}
}
}internal :payload,
type: Hash,
schema: {
request_id: { type: String, required: true },
user: {
type: Hash,
required: true,
first_name: { type: String, required: true },
middle_name: { type: String, required: false, default: "<unknown>" },
last_name: { type: String, required: true },
pass: {
type: Hash,
required: true,
series: { type: String, required: true },
number: { type: String, required: true }
}
}
}output :payload,
type: Hash,
schema: {
request_id: { type: String, required: true },
user: {
type: Hash,
required: true,
first_name: { type: String, required: true },
middle_name: { type: String, required: false, default: "<unknown>" },
last_name: { type: String, required: true },
pass: {
type: Hash,
required: true,
series: { type: String, required: true },
number: { type: String, required: true }
}
}
}Описывайте каждый ожидаемый ключ хеша в таком формате:
{
request_id: { type: String, required: true }
}Допустимые опции: обязательные type, required и опциональные default, prepare. Опции default и prepare доступны только внутри input.
Если type указывает Hash, описывайте вложенность в таком же формате.
Опция must input internal (^2.2.0) output (^2.2.0)
Опция валидации. Создавайте собственные валидации.
class PaymentsService::Create < ApplicationService::Base
input :invoice_numbers,
type: Array,
consists_of: String,
must: {
be_6_characters: {
is: ->(value:, input:) { value.all? { |id| id.size == 6 } }
}
}
# ...
endclass EventsService::Send < ApplicationService::Base
# ...
internal :invoice_numbers,
type: Array,
consists_of: String,
must: {
be_6_characters: {
is: ->(value:, internal:) { value.all? { |id| id.size == 6 } }
}
}
# ...
endclass EventsService::Send < ApplicationService::Base
# ...
output :invoice_numbers,
type: Array,
consists_of: String,
must: {
be_6_characters: {
is: ->(value:, output:) { value.all? { |id| id.size == 6 } }
}
}
# ...
endОпция format input (^2.4.0) internal (^2.4.0) output (^2.4.0)
Динамическая опция валидации (не входит в основные). См. подробнее.
Опция max input (^2.4.0) internal (^2.4.0) output (^2.4.0)
Динамическая опция валидации (не входит в основные). См. подробнее.
Опция min input (^2.4.0) internal (^2.4.0) output (^2.4.0)
Динамическая опция валидации (не входит в основные). См. подробнее.
Опция target input (^3.0.0) internal (^3.0.0) output (^3.0.0)
Динамическая опция валидации для атрибутов типа Class (не входит в основные). См. подробнее.
Опция prepare input
Не является валидацией. Подготавливает переданное значение.
WARNING
Используйте prepare осторожно, только для простых действий. Сложную логику лучше применять через действие make.
class PaymentsService::Create < ApplicationService::Base
input :amount_cents,
as: :amount,
type: Integer,
prepare: ->(value:) { Money.from_cents(value, :USD) }
# ...
def create!
outputs.payment = Payment.create!(amount: inputs.amount)
end
end