Created
June 19, 2026 15:38
-
-
Save havenwood/df0fd84f5d37d02b69ea07e3355b0c22 to your computer and use it in GitHub Desktop.
Parsing Ruby options into Data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'optparse' | |
| module Kernel | |
| def OptionParser(&) | |
| fields = OptionParser.new(&).top.list.filter_map do |option| | |
| if option.is_a?(OptionParser::Switch) | |
| name = option.long&.first || option.short&.first | |
| name.delete_prefix('-').delete_prefix('-').to_sym | |
| end | |
| end | |
| Data.define(*fields) do | |
| define_singleton_method(:parse) do |argv = ARGV| | |
| into = fields.to_h { |field| [field, nil] } | |
| OptionParser.new(&).parse!(argv, into:) | |
| new(**into) | |
| end | |
| end | |
| end | |
| end | |
| Options = OptionParser do |parser| | |
| parser.on('-o', '--output FILE') | |
| parser.on('-p', '--port PORT', Integer) | |
| parser.on('-v', '--verbose') | |
| end | |
| # options = Options.parse(ARGV) | |
| options = Options.parse(%w[-o blah.o -p 3000]) | |
| p options |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment