Arguments
Arguments are the inputs to a service. They are passed to the service when it is invoked.
TL;DR
Define arguments with the
argkeyword in the service classValidate arguments by type
Specify arguments as required or optional
Set default values for arguments
Access arguments like instance variables
Use predicate methods for arguments
class User::Charge < ApplicationService
arg :user, type: User
arg :amount, type: Float
arg :send_receipt, type: [TrueClass, FalseClass], default: true
# In Rails you might prefer `Date.current`.
arg :invoice_date, type: Date, default: -> { Date.today }
step :send_email_receipt, if: :send_receipt?
# ...
endDefine Arguments
Arguments are defined using the arg keyword in the service class.
Type Validation
Arguments can be validated by type.
You can specify multiple allowed types using an array.
Type Enforcement (Enabled by Default)
By default, all arguments must have a type option. This helps catch type-related bugs early and makes your services self-documenting.
To disable type enforcement for arguments in a specific service:
See the Configuration documentation for more details.
Sorbet Runtime Types
Operandi supports Sorbet runtime types for type validation. Sorbet types only validate and do not coerce values.
Sorbet types do NOT coerce values. If you pass "25" where an Integer is expected, it will raise an error instead of converting the string to an integer.
See the Sorbet Runtime Types documentation for more details.
Required Arguments
By default, arguments are required. You can make them optional by setting optional to true.
Default Values
Set a default value for an argument to make it optional.
Complex Default Values
Default values are deep duplicated when the service is invoked, making it safe to use mutable objects.
Procs as Default Values
Use procs for dynamic default values.
Inheritance
Arguments are inherited from parent classes.
Removing Inherited Arguments
To remove an inherited argument, use remove_arg:
Context Arguments
Context arguments are automatically passed to all child services in the same context. Define them using the context option. This is useful for passing objects like current_user.
Learn more about context in the Context documentation.
Accessing Arguments
Arguments are accessible like instance variables, similar to attr_accessor.
Accessing Arguments Using arguments
argumentsFor dynamic access or to avoid conflicts, use the arguments method.
Argument Predicate Methods
Predicate methods are automatically generated for each argument, allowing you to check if an argument is true or false.
What's Next?
Next step is steps (I love this pun). Steps are the building blocks of a service, the methods that do the actual work.
Last updated