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
# 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
......
#
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
......
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
#
......
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)
test/optparse/test_to_h.rb
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
    (1-1/1)