-
-
Save jordansissel/557bc77f58a478cbfa7d072ca94be854 to your computer and use it in GitHub Desktop.
Parsing flags from a file in Clamp in Ruby
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
--version 1.2.3.4 |
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
# 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 |
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
#!/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