Project

General

Profile

Feature #11191 ยป 0001-Add-to_h-method-to-OptionParser.patch

injekt (Lee Jarvis), 05/27/2015 08:44 PM

View differences:

lib/optparse.rb
474 474
  # RequiredArgument, etc.
475 475
  #
476 476
  class Switch
477
    attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
477
    attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block, :value
478 478

  
479 479
    #
480 480
    # Guesses argument style from +arg+.  Returns corresponding
......
543 543
    #
544 544
    def conv_arg(arg, val = [])
545 545
      if conv
546
        val = conv.call(*val)
546
        @value = conv.call(*val)
547 547
      else
548
        val = proc {|v| v}.call(*val)
548
        @value = proc {|v| v}.call(*val)
549 549
      end
550
      return arg, block, val
550
      return arg, block, @value
551 551
    end
552 552
    private :conv_arg
553 553

  
......
883 883
        end
884 884
      end
885 885
    end
886

  
887
    #
888
    # Return a hash of switch names and values.
889
    #
890
    def to_h
891
      list.map { |o| [o.switch_name.to_sym, o.value] }.to_h
892
    end
886 893
  end
887 894

  
888 895
  #
......
1636 1643
  end
1637 1644

  
1638 1645
  #
1646
  # Returns a Hash of switch names and values.
1647
  #
1648
  # This method can be used in place of switch-specific blocks
1649
  # which are used to just set values on a hash.
1650
  #
1651
  # The Hash key will be the switch name as a symbol with
1652
  # leading -- characters removed.
1653
  #
1654
  #   opts = OptionParser.new do |o|
1655
  #     o.on('-h', '--host')
1656
  #     o.on('-p', '--port', Integer)
1657
  #     o.on('-V', '--verbose')
1658
  #   end
1659
  #   opts.parse %w(--host localhost -p80 -V)
1660
  #   opts.to_h #=> {:host=>"localhost", :port=>80, :verbose=>true}
1661
  #
1662
  def to_h
1663
    top.to_h
1664
  end
1665

  
1666
  #
1639 1667
  # Wrapper method for getopts.rb.
1640 1668
  #
1641 1669
  #   params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option)
test/optparse/test_to_h.rb
1
require_relative 'test_optparse'
2

  
3
class TestOptionParser::ToH < TestOptionParser
4
  def setup
5
    super
6
    @opt.def_option("-xVAL")
7
    @opt.def_option("--option=VAL")
8
    @opt.def_option("--verbose")
9
  end
10

  
11
  def test_with_reqarg
12
    @opt.parse("-xfoo")
13
    assert_value(:x, "foo")
14

  
15
    @opt.parse("--option=bar")
16
    assert_value(:option, "bar")
17
  end
18

  
19
  def test_with_noarg
20
    assert_value(:verbose, nil)
21

  
22
    @opt.parse("--verbose")
23
    assert_value(:verbose, true)
24
  end
25

  
26
  def assert_value(key, value)
27
    assert_equal(value, @opt.to_h[key])
28
  end
29
end
0
-