An opinionated implementation of the Command pattern for Ruby applications. Cuprum wraps your business logic in a consistent, object-oriented interface and features status and error management, composability and control flow management.
An Operation is like a Command, but with two key differences. First, an Operation retains a reference to the result object from the most recent time the operation was called, and delegates the methods defined by Cuprum::Result
to the most recent result. This allows a called Operation to replace a Cuprum::Result
in any code that expects or returns a result. Second, the #call
method returns the operation instance, rather than the result itself.
These two features allow developers to simplify logic around calling and using the results of operations, and reduce the need for boilerplate code (particularly when using an operation as part of an existing framework, such as inside of an asynchronous worker or a Rails controller action).
class CreateBookOperation < Cuprum::Operation
def process
# Implementation here.
end
end
# Defining a controller action using an operation.
class BooksController
def create
operation = CreateBookOperation.new
operation.call(book_params)
if operation.success?
redirect_to(operation.value)
else
@book = operation.value
render :new
end
end
end
Like a Command, an Operation can be defined directly by passing an implementation block to the constructor or by creating a subclass that overwrites the #process method.
An operation inherits the #call
method from Cuprum::Command (see above), and delegates the #value
, #error
, #success?
, and #failure
methods to the most recent result. If the operation has not been called, these methods will return default values.
The implementation of Cuprum::Operation
is defined by the Cuprum::Operation::Mixin
module, which provides the methods defined above. Any command class or instance can be converted to an operation by including (for a class) or extending (for an instance) the operation mixin.
Back to Documentation | Commands