Skip to content

Defining Model Items

mosop edited this page Jan 22, 2017 · 5 revisions

To model your command-line options and arguments, define model items using the following API methods:

string

Defines an option whose the String type.

class Model < Optarg::Model
  string "-s"
end

Model.parse(%w(-s foo)).s # "foo"

bool

Defines an option whose the Bool type.

class Model < Optarg::Model
  bool "-b"
end

Model.parse(%w(-b)).b? # true

array

Defines an option whose the Array(String) type.

class Model < Optarg::Model
  array "-a"
end

Model.parse(%w(-a foo -a bar -a baz)).a # ["foo", "bar", "baz"]

arg

Defines an named argument whose the String type.

class Model < Optarg::Model
  arg "arg"
end

Model.parse(%w(foo)).arg # "foo"

arg_array

Defines an named argument whose the Array(String) type.

class Model < Optarg::Model
  arg_array "arg"
end

Model.parse(%w(foo bar baz)).arg # ["foo", "bar", "baz"]

handler

Defines a handler.

class Model < Optarg::Model
  handler("-h") { raise "-h!" }
end

Model.parse(%w(-h)) # raises "-h!"

terminator

Defines a terminator.

class Model < Optarg::Model
  terminator "--"
end

result = Model.parse(%w(foo -- bar))
result.parsed_args # ["foo"]
result.unparsed_args # ["bar"]
Clone this wiki locally