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.
Functional implementation for creating a command object. Cuprum::Processing defines a #call method, which performs the implementation defined by #process and returns an instance of Cuprum::Result.
Defining a command with Cuprum::Processing.
class AdderCommand
include Cuprum::Processing
def initialize addend
@addend = addend
end
private
def process int
int + addend
end
end
adder = AdderCommand.new(2)
result = adder.call(3)
#=> an instance of Cuprum::Result
result.value #=> 5
result.success? #=> trueDefining a command with error handling.
class SquareRootCommand
include Cuprum::Processing
private
def process value
if value.negative?
return Cuprum::Result.new(error: 'value cannot be negative')
end
Math.sqrt(value)
end
end
result = SquareRootCommand.new.call(2)
result.value #=> 1.414
result.success? #=> true
result.failure? #=> false
result.error #=> nil
result = SquareRootCommand.new.call(-1)
result.value #=> nil
result.success? #=> false
result.failure? #=> true
result.error #=> 'value cannot be negative'#arity => Integer
Returns an indication of the number of arguments accepted by #call.
If the method takes a fixed number N of arguments, returns N. If the method takes a variable number of arguments, returns -N-1, where N is the number of required arguments. Keyword arguments will be considered as a single additional argument, that argument being mandatory if any keyword argument is mandatory.
#call(*arguments, **keywords, &block) => Cuprum::Result
Executes the command and returns a Cuprum::Result or compatible object.
Each time #call is invoked, the object performs the following steps:
#process(*arguments, **keywords, &block) => Cuprum::Result, Object
Note: This is a private method.
The implementation of the command.
Whereas the #call method provides the public interface for calling a command, the #process method defines the actual implementation. This method should not be called directly.
When the command is called via #call, the parameters are passed to #process. If #process returns a result, that result will be returned by #call; otherwise, the value returned by #process will be wrapped in a successful Cuprum::Result object.
Back to Documentation | Versions | 1.3 | Reference | Cuprum