diff options
author | Noah Kantrowitz <noah@coderanger.net> | 2016-06-16 18:55:23 -0700 |
---|---|---|
committer | Noah Kantrowitz <noah@coderanger.net> | 2016-06-16 18:55:23 -0700 |
commit | b7043c598293bfd74fbbfa7a9ce9edc4c2724c03 (patch) | |
tree | d7497aca787d403fcba092904b51b275dac773a7 | |
parent | 2e2670b7664acda8b5c48da7a7b71f5b775ff07d (diff) | |
download | mixlib-cli-b7043c598293bfd74fbbfa7a9ce9edc4c2724c03.tar.gz |
Support two-argument procs for reducer-style arguments. This allows CLI options which can be repeated.
-rw-r--r-- | lib/mixlib/cli.rb | 13 | ||||
-rw-r--r-- | spec/mixlib/cli_spec.rb | 10 |
2 files changed, 22 insertions, 1 deletions
diff --git a/lib/mixlib/cli.rb b/lib/mixlib/cli.rb index 31e44be..3e72f77 100644 --- a/lib/mixlib/cli.rb +++ b/lib/mixlib/cli.rb @@ -281,7 +281,18 @@ module Mixlib parse_block = Proc.new() do |c| - config[opt_key] = (opt_val[:proc] && opt_val[:proc].call(c)) || c + config[opt_key] = if opt_val[:proc] + if opt_val[:proc].arity == 2 + # New hotness to allow for reducer-style procs. + opt_val[:proc].call(c, config[opt_key]) + else + # Older single-argument proc. + opt_val[:proc].call(c) + end + else + # No proc. + c + end puts opts if opt_val[:show_options] exit opt_val[:exit] if opt_val[:exit] end diff --git a/spec/mixlib/cli_spec.rb b/spec/mixlib/cli_spec.rb index 39b1eb1..0115672 100644 --- a/spec/mixlib/cli_spec.rb +++ b/spec/mixlib/cli_spec.rb @@ -149,6 +149,16 @@ describe Mixlib::CLI do @cli.config[:number].should == 4 end + it "should pass the existing value to two-argument procs" do + TestCLI.option(:number, + :short => "-n NUMBER", + :proc => Proc.new { |value, existing| existing ||= []; existing << value; existing } + ) + @cli = TestCLI.new + @cli.parse_options([ "-n", "2", "-n", "3" ]) + @cli.config[:number].should == ["2", "3"] + end + it "should set the corresponding config value to true for boolean arguments" do TestCLI.option(:i_am_boolean, :short => "-i", :boolean => true) @cli = TestCLI.new |