-
Notifications
You must be signed in to change notification settings - Fork 7
Accessing Values
To access named values, use value accessors or value hashes.
If you define a named value, a corresponding value accessor is automatically defined.
A value accessor name is determined by a value name. Any leading minus signs (-) are eliminated and other minus signs are converted to underscore letters (_). For example, --option-name is converted to option_name.
If a value type is Bool, the corresponding accessor name has a trailing ? mark.
class Model < Optarg::Model
string "-s"
bool "-b"
array "-a"
arg "arg"
arg_array "args"
end
result = Model.parse(%w(-s foo -b -a bar -a baz blep blah boop))
result.s # "foo"
result.b? # true
result.a # ["bar", "baz"]
result.arg # "blep"
result.args # ["blah", "boop"]If a value type is Bool and the value is undefined, the corresponding value accessor returns false.
class Model < Optarg::Model
bool "-b"
end
result = Model.parse(%w())
result.b? # falseIf a value type is String, a nilable accessor is also defined. The nilable accessor returns nil if the value is undefined.
class Model < Optarg::Model
string "-s"
end
result = Model.parse(%w())
result.s # raises an error
result.s? # nilIf a value has multiple names, multiple accessors are defined.
class Model < Optarg::Model
bool %w(-f --force)
end
result = Model.parse(%w(--force))
result.f? # true
result.force? # trueA value hash is a Hash object that each model instance creates for storing parsed values.
To access the value hashes, call the model instance's [] method with a value class.
class Model < Optarg::Model
string "-s"
bool "-b"
array "-a"
arg "arg"
arg_array "args"
end
result = Model.parse(%w(-s foo -b -a bar -a baz blep blah boop))
result[String] # {"-s" => "foo", "arg" => "blep"}
result[Bool] # {"-b" => true}
result[Array(String)] # {"-a" => ["bar", "baz"], "args" => ["blah", "boop"]}If a value has multiple names, only the first name can be used as a hash key.
class Model < Optarg::Model
bool %w(-f --force)
end
result = Model.parse(%w(--force))
result[Bool]["-f"] # true
result[Bool]["--force"] # raises an errorIf a value accessor name is already used in the ancestor classes (Optarg::Model, Reference and Object), the accessor won't be defined and the method won't be overriden.
In this case, you can still access parsed values by value hashes.
class Model < Optarg::Model
string "--class"
end
result = Model.parse(%w(--class foo))
result.class # Model
result[String]["--class"] # "foo"class Model < Optarg::Model
arg "arg"
end
result = Model.parse(%w(foo bar baz))
result.arg # "foo"
result.nameless_args # ["bar", "baz"]class Model < Optarg::Model
arg "arg", stop: true
end
result = Model.parse(%w(foo bar baz))
result.arg # "foo"
result.unparsed_args # ["bar", "baz"]class Model < Optarg::Model
terminator "--"
end
result = Model.parse(%w(foo -- bar baz))
result.nameless_args # ["foo"]
result.unparsed_args # ["bar", "baz"]