Outputs are the results of a service.
- Define outputs using the
outputkeyword in the service class - Outputs can have default values
- Outputs can be validated by type [In Development]
You define outputs using the output keyword in the service class.
class AI::Chat < ApplicationService
output :messages
output :cost
endOutputs function similarly to instance variables created with attr_accessor.
class AI::Chat < ApplicationService
# Steps
step :chat
# Outputs
output :messages
output :cost
private
def chat
self.messages = ["Hello!", "Hi, how are you?"]
self.cost = 0.0013
end
endTo set outputs programmatically, use the outputs.set method or hash syntax.
class AI::Chat < ApplicationService
# ...
def chat
outputs.set(:messages, ["Hello!", "Hi, how are you?"])
outputs.set(:cost, 0.0013)
# Or use hash syntax
outputs[:messages] = ["Hello!", "Hi, how are you?"]
outputs[:cost] = 0.0013
end
endYou can specify the type of output using the type option. The output type will be validated when the service successfully completes.
class AI::Chat < ApplicationService
output :messages, type: Array
output :cost, type: :float
endYou can specify multiple allowed types using an array.
class AI::Chat < ApplicationService
output :result, type: [String, Hash]
endSet default values for outputs using the default option. The default value will be automatically set before the execution of steps.
class AI::Chat < ApplicationService
output :cost, default: 0.0
endWhen inheriting from a parent service, you can remove outputs using remove_output:
class BaseReportService < ApplicationService
output :report
output :debug_info
end
class ProductionReportService < BaseReportService
# Don't expose debug info in production
remove_output :debug_info
endNext, learn about context.