While you typically return Success and Failure from operation steps, you can also use other monads from Dry Monads. These are automatically converted to a Result when you pass them to #step.
Try for exception handling
The Try monad is useful for wrapping code that may raise exceptions. When used with #step, any caught exception becomes a Failure:
include Dry::Monads[:try]
# If File.read raises Errno::ENOENT, or JSON.parse raises JSON::ParserError, step will receive a
# Failure and short-circuit the operation
content = step Try { File.read(file_path) }
data = step Try { JSON.parse(content) }
step save_to_database(data)
:imported
end
end
You can also specify which exceptions to catch:
step Try[Errno::ENOENT, Errno::EACCES] { File.read(file_path) }
Maybe for nil handling
The Maybe monad converts nil values to None and non-nil values to Some. These become Failure and Success respectively when converted to a Result.
include Dry::Monads[:maybe]
# If find_user returns nil, Maybe(nil) becomes None, which converts to Failure
user = step Maybe(find_user(user_id))
# If user.profile is nil, this will also fail
profile = step Maybe(user.profile)
profile
end
private
# Returns user or nil
User.find_by(id:)
end
end
A None converts to a Failure with no value (Failure()). If you need to tell failures apart, convert the Maybe yourself and give a failure value:
user = step Maybe(find_user(user_id)).to_result(:user_not_found)
Validated for validation with error accumulation
The Validated type is useful when you want to collect multiple validation errors instead of failing on the first one. Combine Validated values with List, then pass the result to #step:
include Dry::Monads[:list, :validated]
name, email, age = step List::Validated[
validate_name(input),
validate_email(input),
validate_age(input)
].traverse
{name:, email:, age:}
end
private
# Valid(name) or Invalid(:invalid_name)
end
# Valid(email) or Invalid(:invalid_email)
end
# Valid(age) or Invalid(:invalid_age)
end
end
When any validation fails, the Failure includes all the collected errors:
ValidateUserInput.new.call(input)
# => Failure(List[:invalid_name, :invalid_email])
Including monads in your operations
To use one or more monads (other than Result) in your operations, specify them when including Dry::Monads.
include Dry::Monads[:try, :maybe, :validated]
# Now you can use Try, Maybe, and Validated
end
end
The Result monad is always available through the Success and Failure constructors that Dry Operation provides, so you don’t need to explicitly include it.
Result conversion via #to_result
The #step method calls #to_result on any object given to it, expecting a Dry::Monads::Success or Dry::Monads::Failure (or any other object responding to #value_or) in return. Implement this protocol on your own objects to make them compatible with steps.
@errors = errors
@value = value
end
if @errors.empty?
Dry::Monads::Success(@value)
else
Dry::Monads::Failure(@errors)
end
end
end
attrs = step check(input) # returns a ValidationOutcome
# ...
end
end
If you pass #step an object that does not respond to #to_result, it raises a Dry::Operation::InvalidStepResultError.