Skip to content

Instantly share code, notes, and snippets.

@jordansissel
Last active May 19, 2022
Embed
What would you like to do?
Parsing flags from a file in Clamp in Ruby
--version 1.2.3.4
# Reading flags from the given `--config-file` path should work :)
% ruby test.rb --version 5.5.5.5 --config-file /tmp/conf
Version: 1.2.3.4
#!/usr/bin/env ruby
#
require "clamp"
require "shellwords"
require "pry"
class Foo < Clamp::Command
option "--config-file", "FILE", "Load additional options (flags) from a given file." do |path|
# Parse the file
File.read(path).split("\n").each do |line|
# Parse each line of the file as a "shell" syntax splitting into shell words.
args = Shellwords.split(line)
# Process arguments from this line
while args.any?
# The steps in this file are based on Clamp's Option::Parsing#handle_switch method.
arg = args.shift
# Lookup the flag by its --flag-name
option = self.class.find_option(arg)
# Extract the flag value, if any, from the remaining args list.
value = option.extract_value(arg, args)
# Process the flag into `self`
option.of(self).take(value)
end
end
end
option "--version", "VERSION", "The version", :default => "1.0"
def execute
puts "Version: #{version}"
end
end
Foo.run($0, ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment