Search code examples
stringterminaldartinterpolationwritefile

Dart string interpolation through console run script


I'm using Dart to generate controller classes into the project framework using a script I've made in the tool directory. The script is run using the following terminal command (whilst in the project directory of course):

dart tool/controller_create.dart controllerName

This runs the following script and uses string interpolation to inject the name into the necessary areas, taking the first parameter 'controllerName' from the console to be used as the value for the 'name' variable in the script:

import 'dart:io';

void main(String name)
{
  String content = """
  part of controllers;

  class $name extends Controller
  {
    //-------------------------------------------------------------------------------------------
    // Functions
    //-------------------------------------------------------------------------------------------

    /**
     * Passes parameters and initialises superclass constructor
     */

    $name () : super(new VirtualDirectory(root_package_dir))
    {
      virtualDirectory.allowDirectoryListing = false;
      virtualDirectory.jailRoot = true;
    }

    //-------------------------------------------------------------------------------------------
    // Functions - Controllers
    //-------------------------------------------------------------------------------------------

    void index (HttpRequest request)
    {
      virtualDirectory.serveFile(new File(views_dir + "/index.html"), request);
    }
  }
  """;

  new File('$name.dart').writeAsString(content).then((File file)
  {

  });
}

However, the problem I've come across is that the given string doesn't just inject 'controllerName' into the specified areas, but rather '[controllerName]', and leaves me wondering what causes this and how can I avoid it?

Thank you for reading! This is the first terminal driven script I've made so I apologise if this is normal behaviour for terminal passed variables.


Solution

  • Despite your method signature for main, command line arguments are actually passed as List<String>. Therefore string interpolation sees a list containing one element, controllerName.

    Change main to void main(List<String> args) and create a new field var name = args[0].