Skip to content

Parsing Options

mosop edited this page Jan 18, 2018 · 16 revisions

Integration with optarg

Crystal CLI integrates its API with optarg. optarg is a library for parsing command-line options and arguments.

Once you define a command class, the class automatically has an optarg's model class that is named Options. You can define options and arguments inside the Options class.

class Smile < Cli::Command
  class Options
    bool "--say-hello"
  end
end

To access parsed values in a running context, use the following methods:

  • options
  • args
  • nameless_args
  • unparsed_args
class Smile < Cli::Command
  class Options
    bool "--say-hello"
  end

  def run
    print "hello " if options.say_hello?
    puts ":)"
  end
end

Smile.run %w(--say-hello)

This prints:

hello :)

Accessing a Command Instance

You can access a command instance in optarg's contexts with the command method.

class Smile < Cli::Command
  class Options
    on("--say-hello") { command.say_hello }
  end

  def say_hello
    print "hello "
  end

  def run
    puts ":)"
  end
end

Smile.run %w(--say-hello)

This prints:

hello :)