Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the default: option in Yeoman depending on a previous answer?

Tags:

gruntjs

yeoman

I'm curious if it's possible to change the default message of a prompt depending on what the user selected from a previous prompt.

Right now my first prompt is just a list where the user selects one option and is asked a few other questions. Note that these two run in two different generators

YeomanGenerator.prototype.askForThings = function askForThings() {
  var cb = this.async();
  var prompts = [{
    name: 'questionOne',
    type: 'list',
    message: 'Message, message?',
    choices: ['optionOne', 'optionTwo', 'optionThree', 'optionFour', 'optionFive', 'optionSix', 'None'],
    filter: function(value) { 
      return value.toLowerCase(); 
    }
  }

Then, in the next section the user is asked in which directory to place this. However, I'm wondering if it's possible to change the default location depending on what the user selected in questionOne. Right now the default option just comes out empty.

YeomanGenerator.prototype.askForMoreThings = function askForMoreThings() {
  var cb = this.async();

  var questionOne = this.questionOne;

    {
      name: 'questionOneDirectory',
      message: 'Question question',
      default: function(default) {
        if (this.questionOne === 'optionOne') {
          this.default("'/directory/_one'");
        }
        else if (this.questionOne === 'optionTwo') {
          this.default("'/directory/_two'");
        }
        { 
          //etc 
        }
      },
      filter: function(value) { return value.split('/').pop(); },
      when: function() {
        return questionOne;
      },

Is it even possible to change the default message here? It's just a minor things but I'm wondering if it's at all possible. Thanks in advance.

like image 657
Sondre Nilsen Avatar asked Feb 01 '14 01:02

Sondre Nilsen


1 Answers

Here is a generic solution for those who search the answer to the question topic. default property accepts a function and passes an object with all previous answers to it. Use that object to generate defaults in runtime:

this.prompt([{
  name: 'title',
  message: 'Your title?',
  default: 'Mr.'
}, {
  name: 'name',
  message: 'Your name?',
  default: function(answers) {
    return answers.title + ' Smith';
  }
}]);
like image 63
whyleee Avatar answered Nov 05 '22 21:11

whyleee