From 7565745c40ab37d07041c05422b9a53487564c09 Mon Sep 17 00:00:00 2001 From: Lee Jarvis Date: Wed, 27 May 2015 21:22:08 +0100 Subject: [PATCH 1/1] Add to_h method to OptionParser This method returns a Hash of switch name and value key pairs --- lib/optparse.rb | 36 ++++++++++++++++++++++++++++++++---- test/optparse/test_to_h.rb | 29 +++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 test/optparse/test_to_h.rb diff --git a/lib/optparse.rb b/lib/optparse.rb index b83938b..09d52bc 100644 --- a/lib/optparse.rb +++ b/lib/optparse.rb @@ -474,7 +474,7 @@ class OptionParser # RequiredArgument, etc. # class Switch - attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block + attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block, :value # # Guesses argument style from +arg+. Returns corresponding @@ -543,11 +543,11 @@ class OptionParser # def conv_arg(arg, val = []) if conv - val = conv.call(*val) + @value = conv.call(*val) else - val = proc {|v| v}.call(*val) + @value = proc {|v| v}.call(*val) end - return arg, block, val + return arg, block, @value end private :conv_arg @@ -883,6 +883,13 @@ class OptionParser end end end + + # + # Return a hash of switch names and values. + # + def to_h + list.map { |o| [o.switch_name.to_sym, o.value] }.to_h + end end # @@ -1636,6 +1643,27 @@ XXX end # + # Returns a Hash of switch names and values. + # + # This method can be used in place of switch-specific blocks + # which are used to just set values on a hash. + # + # The Hash key will be the switch name as a symbol with + # leading -- characters removed. + # + # opts = OptionParser.new do |o| + # o.on('-h', '--host') + # o.on('-p', '--port', Integer) + # o.on('-V', '--verbose') + # end + # opts.parse %w(--host localhost -p80 -V) + # opts.to_h #=> {:host=>"localhost", :port=>80, :verbose=>true} + # + def to_h + top.to_h + end + + # # Wrapper method for getopts.rb. # # params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option) diff --git a/test/optparse/test_to_h.rb b/test/optparse/test_to_h.rb new file mode 100644 index 0000000..669644d --- /dev/null +++ b/test/optparse/test_to_h.rb @@ -0,0 +1,29 @@ +require_relative 'test_optparse' + +class TestOptionParser::ToH < TestOptionParser + def setup + super + @opt.def_option("-xVAL") + @opt.def_option("--option=VAL") + @opt.def_option("--verbose") + end + + def test_with_reqarg + @opt.parse("-xfoo") + assert_value(:x, "foo") + + @opt.parse("--option=bar") + assert_value(:option, "bar") + end + + def test_with_noarg + assert_value(:verbose, nil) + + @opt.parse("--verbose") + assert_value(:verbose, true) + end + + def assert_value(key, value) + assert_equal(value, @opt.to_h[key]) + end +end -- 2.2.2