dthree / vorpal

Node's framework for interactive CLIs

Home Page:http://vorpal.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[2.0 Proposition] Using a this less API

AdrieanKhisbe opened this issue · comments

Proposition

We should take the opportunity of the incoming v2 to adopt a thisless 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();
  });