vorpal
vorpal copied to clipboard
[2.0 Proposition] Using a this less API
Proposition
We should take the opportunity of the incoming v2 to adopt a this
less api.
This will make action handler far more easy to test without having to mock a vorpal instance.
The function would be injected with a single arguments, an object holding the args
, the options
, the logger and the callback.
Example
Original Code
vorpal
.command('foo <requiredArg> [optionalArg]')
.option('-v, --verbose', 'Print foobar instead.')
.action(function(args, callback) {
if (args.options.verbose) {
this.log('foobar ' + args.requiredArg);
} else {
this.log('bar ' + (args.optionalArg || 'default')));
}
callback();
});
V2 proposed code
vorpal
.command('foo <requiredArg> [optionalArg]')
.option('-v, --verbose', 'Print foobar instead.')
.action(function(cmd) {
if (cmd.options.verbose) {
cmd.log('foobar ' + cmd.args.requiredArg);
} else {
cmd.log('bar ' + (cmd.args.optionalArg || 'default')));
}
cmd.callback();
});
alternative usage with destructuring:
vorpal
.command('foo <requiredArg> [optionalArg]')
.option('-v, --verbose', 'Print foobar instead.')
.action(function({options, args, log, callback}) {
if (options.verbose) {
log('foobar ' + args.requiredArg);
} else {
log('bar ' + (args.optionalArg || 'default')));
}
callback();
});