Overview
TheOpts utility provides a generic CLI argument parser for any command-line parsing task. It separates concerns between parsing, validation, and execution, returning an immutable OpenStruct with typed values.
Location: lib/util/opts.rb
Class Methods
parse
Parse an argument array (typicallyARGV) into an immutable OpenStruct based on a schema definition.
Argument list to parse (usually
ARGV)Option definitions with metadata. Each key represents an option name, and the value is a hash with:
:type(Symbol) - Type coercion::string,:boolean,:integer, or:array:default(Object) - Default value if not provided:parser(Proc) - Custom parser function for complex transformations:short(String) - Short form flag (e.g., “v” for “-v”)
Frozen OpenStruct with all specified keys from the schema
Examples
Basic Usage
Boolean Flags
Custom Parser
Integer Type
Array Type
Short Flags
Argument Formats
The parser supports multiple argument formats:- Boolean flags:
--verboseor-v - Separate value:
--port 8080 - Equals syntax:
--port=8080 - Multiple values (array):
--files a.txt b.txt c.txt
max_connections → --max-connections).
Type Coercion
| Type | Behavior |
|---|---|
:boolean | Presence of flag sets to true. With = syntax: matches true/on/yes/1 (case-insensitive) |
:string | Takes next argument or value after = |
:integer | Converts to integer using .to_i |
:array | Collects all following arguments until next flag |
Custom :parser | Calls provided Proc with the value string |
Immutability
The returnedOpenStruct is frozen, making the parsed options immutable. This prevents accidental modification and makes the options safe to pass around.
