Dry Operation is the successor to Dry Transaction. Both libraries support Railway Oriented Programming, but Dry Operation offers a more flexible approach.
Dry Operation has an alternative for every Dry Transaction feature, so you can migrate all your transaction classes.
Key differences
With Dry Transaction, you declare steps at the class level, and each step’s output becomes the next step’s input. With Dry Operation, you write your steps as ordinary Ruby inside your operation’s #call method:
- Each step is a method call wrapped with
#step. If the method returns aSuccess,#stepreturns its value. If it returns aFailure, the operation stops and returns that failure. - You pass data between steps yourself. This means you can adjust values between steps, and your steps can have any signature.
- Steps have no names. To tell failures apart, return a
Failurewith an identifier, such asFailure[:validate, errors]. - Operations wrap the return value of
#callin aSuccessfor you.
Quick reference
| Dry Transaction | Dry Operation |
|---|---|
step |
A method call wrapped with #step, inside #call
|
map |
A plain method call |
try |
The Try monad, or begin/rescue
|
check |
A conditional that returns a Failure
|
tee |
A plain method call |
| Custom step adapters | A plain method |
Containers and with: |
Dependency injection |
#with_step_args |
Arguments to #call
|
| Step notifications | Your own pub/sub, plus the #on_failure hook |
around steps |
The database extensions |
| Match blocks | Pattern matching with case/in
|
Migrating a simple transaction
Move your class-level steps into your operation’s #call method. Use the return value of each step to prepare the input for the next step, and pass it explicitly.
Dry Transaction
include Dry::Transaction
step :validate
step :create
private
# Returns Success(attrs) or Failure(errors)
end
# Returns Success(user) or Failure(error)
end
end
Dry Operation
attrs = step validate(input)
step create(attrs)
end
private
# Returns Success(attrs) or Failure(errors)
end
# Returns Success(user) or Failure(error)
end
end
You call both classes in the same way, and both return a Success or Failure:
result = CreateUser.new.call(name: "Jane", email: "jane@example.com")
result.success?
If your validate step uses Dry Validation, you can replace it with the Validation extension. This validates your operation’s input before #call runs.
Step adapters
Dry Transaction’s step adapters (map, try, check, tee) are a class-level DSL for handling step return values. With Dry Operation, you use plain Ruby, or other monads from Dry Monads. See Other monads for how these work with #step.
map: wrapping raw values
A map step can’t fail, so you don’t need #step at all. Call the method directly.
Dry Transaction
include Dry::Transaction
map :process # Wraps the return value in Success
step :create
end
Dry Operation
attrs = process(input)
step create(attrs)
end
private
input.merge(processed: true)
end
# Returns Success(user) or Failure(error)
end
end
try: exception handling
Use the Try monad, or your own begin/rescue.
Dry Transaction
include Dry::Transaction
try :fetch, catch: NetworkError
step :process
end
Dry Operation
include Dry::Monads[:try]
data = step fetch(input)
step process(data)
end
private
# #step converts the Try to a Success or Failure
Try[NetworkError] { HTTP.get("/data/") }
end
Success(data.transform)
end
end
Or with begin/rescue:
Success(HTTP.get("/data/"))
rescue NetworkError => e
Failure(e)
end
check: boolean checks
Return a Failure from a conditional.
Dry Transaction
include Dry::Transaction
check :valid?
step :create
end
Dry Operation
return Failure(:invalid) unless valid?(input)
step create(input)
end
private
input[:name] && input[:email]
end
# Returns Success(user) or Failure(error)
end
end
If you want a nil value to cause a failure, you can also use the Maybe monad. See Other monads.
tee: side effects
Call the method directly between steps. Its return value is ignored.
Dry Transaction
include Dry::Transaction
step :create
tee :notify # Runs for side effects, and passes its input through
end
Dry Operation
user = step create(input)
notify(user)
user
end
private
# Returns Success(user) or Failure(error)
end
Mailer.send_welcome(user)
end
end
Custom step adapters
Dry Transaction lets you register your own step adapters, such as an enqueue adapter that runs a step in a background queue. With Dry Operation, write a plain method that does the same work, and call it from #call.
Dry Transaction
register :enqueue, -> step, input, *args {
BackgroundQueue.push(step.operation, input, *args)
Dry::Monads.Success(input)
}
end
include Dry::Transaction(container: Container, step_adapters: MyStepAdapters)
step :create
enqueue :send_welcome_email
end
Dry Operation
user = step create(input)
enqueue(:send_welcome_email, user)
user
end
private
BackgroundQueue.push(job_name, *args)
end
end
To share this behavior across operations, put the method in a module, or in a base operation class.
External steps
Dry Transaction uses a container to supply external steps, and the with: option to name them. With Dry Operation, make these steps available to your operation as dependencies.
Dry Transaction
extend Dry::Container::Mixin
register "users.validate" do
Users::Validate.new
end
register "users.create" do
Users::Create.new
end
end
include Dry::Transaction(container: Container)
step :validate, with: "users.validate"
step :create, with: "users.create"
end
Dry Operation
In a Hanami app, use the Deps mixin. Use the same approach with Dry Auto Inject outside Hanami.
include Deps[validate: "users.validate", create: "users.create"]
attrs = step validate.call(input)
step create.call(attrs)
end
end
Without a container, accept the dependencies in your initializer:
attr_reader :validate, :create
@validate = validate
@create = create
super()
end
attrs = step validate.call(input)
step create.call(attrs)
end
end
Both approaches also replace Dry Transaction’s support for injecting step objects at runtime. Pass a different object to the initializer, such as a test double:
CreateUser.new(create: -> attrs { Dry::Monads::Failure(:could_not_create) })
Passing step arguments
Dry Transaction passes each step’s output as the next step’s input. To give a step extra arguments, you must call #with_step_args from outside the transaction.
With Dry Operation, you pass arguments to each step yourself, inside #call. Give your operation the extra arguments it needs, and pass them on to the steps.
Dry Transaction
include Dry::Transaction
step :validate
step :create
tee :notify
# ...
end
CreateUser.new
.with_step_args(
create: [account_id: 123],
notify: ["admin@example.com"]
)
.call(name: "Jane")
Dry Operation
attrs = step validate(input)
user = step create(**attrs, account_id:)
notify(user, notification_recipient:)
user
end
# ...
end
CreateUser.new.call(
{name: "Jane"},
account_id: 123,
notification_recipient: "admin@example.com"
)
Step notifications
Dry Operation has no built-in step notifications. Instead, publish your own events using a gem like Dry Events, or with plain Ruby. Use the #on_failure hook to publish an event when the operation fails.
Dry Transaction
include Dry::Transaction
step :validate
step :create
end
extend self
# Called when the step starts
end
# Called when the step succeeds
end
# Called when the step fails
end
end
create_user = CreateUser.new
create_user.subscribe(create: UserCreationListener)
Dry Operation
Using Dry Events:
include Dry::Events::Publisher[:create_user]
register_event "step.succeeded"
register_event "step.failed"
attrs = step validate(input)
publish("step.succeeded", step: :validate, result: attrs)
user = step create(attrs)
publish("step.succeeded", step: :create, result: user)
user
end
private
publish("step.failed", failure:)
end
end
extend self
# event[:step], event[:result]
end
# event[:failure]
end
end
create_user = CreateUser.new
create_user.subscribe(UserCreationListener)
Around steps (database transactions)
Dry Transaction uses around steps to wrap all the steps that follow. This is typically used to roll back a database transaction when a step fails. With Dry Operation, use the database extensions instead.
Dry Transaction
include Dry::Transaction(container: Container)
around :transaction, with: "transaction"
step :create_user, with: "users.create"
step :create_account, with: "accounts.create"
end
Dry Operation
include Dry::Operation::Extensions::ActiveRecord
transaction do
user = step create_user(input)
step create_account(user)
user
end
end
end
These extensions are available:
Result matching
Both Dry Transaction and Dry Operation return a Result, and you can use its full API in both cases.
Dry Operation does not support Dry Transaction’s match blocks. Instead, use pattern matching with case/in.
Dry Transaction’s m.failure(:validate) matches failures by step name. Dry Operation steps have no names, so return a Failure with an identifier from each step you want to match.
Dry Transaction
CreateUser.new.call(input) do
m.success { puts "Created: " }
m.failure(:validate) { puts "Validation failed: " }
m.failure { puts "Error: " }
end
Dry Operation
attrs = step validate(input)
step create(attrs)
end
private
errors = check_for_errors(input)
if errors.any?
Failure[:validate, errors]
else
Success(input)
end
end
# Returns Success(user) or Failure(error)
end
end
Then use pattern matching to handle the result:
case CreateUser.new.call(input)
in Success(user)
puts "Created: "
in Failure[:validate, errors]
puts "Validation failed: "
in Failure(error)
puts "Error: "
end
See the pattern matching documentation for more details.