Skip to content

Instantly share code, notes, and snippets.

@jordansissel
Last active May 19, 2022 08:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordansissel/557bc77f58a478cbfa7d072ca94be854 to your computer and use it in GitHub Desktop.
Save jordansissel/557bc77f58a478cbfa7d072ca94be854 to your computer and use it in GitHub Desktop.
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