-
Notifications
You must be signed in to change notification settings - Fork 6
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.
If 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"
bool "-b"
end
result = Model.parse(%w())
result.s # raises an error
result.s? # nil
result.b? # false
If a value has multiple names, multiple accessor is defined.
class Model < Optarg::Model
bool %w(-f --force)
end
result = Model.parse(%w(--force))
result.f? # true
result.force? # true
A value hash is a Hash object that each model instance creates for storing parsed values.
To access hash objects, use the model instance's [] method with a value class.
class Model < Optarg::Model
string "-s1"
string "-s2"
bool "-b1"
bool "-b2"
array "-a1"
array "-a2"
arg "arg1"
arg "arg2"
arg_array "args"
end
result = Model.parse(%w(-s1 a -s2 b -b1 -b2 -a1 c -a1 d -a2 e -a2 f g h i j))
result[String] # {"-s1" => "a", "-s2" => "b", "arg1" => "g", "arg2" => "h"}
result[Bool] # {"-b1" => true, "-b2" => true}
result[Array(String)] # {"e" => ["c", "d"], "f" => ["e", "f"], "args" => ["i", "j"]}
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 error