ruby
46 lines · 8 steps
Parsing CLI options with OptionParser
Ruby's standard OptionParser turns raw argv into a typed, validated options struct for a command-line tool.
Explained by
highlit
1require 'optparse'
2require 'ostruct'
3
4def parse_options(argv)
5 options = OpenStruct.new(
6 verbose: false,
7 format: :json,
8 workers: 1,
9 tags: []
10 )
11
12 parser = OptionParser.new do |opts|
13 opts.banner = 'Usage: deploy [options] TARGET'
14
15 opts.on('-v', '--[no-]verbose', 'Run with verbose output') do |v|
16 options.verbose = v
17 end
18
19 opts.on('-f', '--format FORMAT', %i[json yaml text],
20 'Output format (json, yaml, text)') do |fmt|
21 options.format = fmt
22 end
23
24 opts.on('-w', '--workers N', Integer, 'Number of parallel workers') do |n|
25 raise OptionParser::InvalidArgument, n.to_s unless n.positive?
26 options.workers = n
27 end
28
29 opts.on('-t', '--tag TAG', 'Filter by tag (repeatable)') do |tag|
30 options.tags << tag
31 end
32
33 opts.on('-c', '--config FILE', 'Path to config file') do |path|
34 options.config = File.expand_path(path)
35 end
36
37 opts.on('-h', '--help', 'Show this message') do
38 puts opts
39 exit
40 end
41 end
42
43 parser.parse!(argv)
44 options.target = argv.shift
45 options
46end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Seeding a defaults object up front means every flag is optional and unset values still behave sensibly.
- 2OptionParser can coerce and validate arguments inline, rejecting bad input before your program logic runs.
- 3parse! mutates argv in place, leaving non-option arguments behind for you to consume as positionals.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-cli-options-with-optionparser-explained-ruby-3b8b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.