module OptionBinder::Switch
Public Class Methods
parser_opts_from_hash(hash = {}, &handler)
click to toggle source
# File lib/optbind.rb, line 140 def self.parser_opts_from_hash(hash = {}, &handler) p = (hash[:style] || hash[:mode]).to_s.upcase style = [(p.to_sym if %w(REQUIRED OPTIONAL).include? p), (:MULTIPLE if hash[:multiple])] pattern = hash[:pattern] || hash[:type] values = hash[:values] names = [hash[:long], hash[:longs]].flatten.map { |n| n.to_s.sub(/\A-{,2}/, '--') if n } names += [hash[:short], hash[:shorts]].flatten.map { |n| n.to_s.sub(/\A-{,2}/, '-') if n } names += [hash[:name], hash[:names]].flatten.map do |n| next unless n n = n.to_s next n if n[0] == '-' n[2] ? "--#{n}" : "-#{n}" end argument = (hash[:argument].to_s.sub(/\A(\[)?=?/, '=\1') if hash[:argument]) description = ([hash[:description]] * ' ' if hash[:description]) handler ||= hash[:handler] return (style + [pattern, values] + names + [argument, description]).compact, handler end
parser_opts_from_string(string = '', &handler)
click to toggle source
# File lib/optbind.rb, line 160 def self.parser_opts_from_string(string = '', &handler) string, shorts, longs = string.dup, [], [] while string.sub!(/\A(?:(?<short>-\w)\s+)/, '') do shorts << $~[:short] end style, pattern, values, argument = [], nil while string.sub!(/\A(?:(?<long>--[\[\]\-\w]+[\]\w]+)?(?:(?<argument>(?:\[?=?|=\[)[<(]\S+[)>]\.{,3}\]?)|\s+))/, '') longs << $~[:long] if $~[:long] next unless $~[:argument] argument = $~[:argument] style = [argument =~ /\A=?[<(]/ ? :REQUIRED : :OPTIONAL, argument =~ /\.{3}\]?\z/ ? :MULTIPLE : nil] values = $~[:values].split('|') if argument =~ /(?:\[?=?|=\[)\((?<values>\S*)\)\]?/ if values.nil? && argument =~ /(?:\[?=?|=\[)<(?<name>\S+):(?<pattern>\S+)>\]?/ argument, pattern = "=<#{$~[:name]}>#{'...' if style.include? :MULTIPLE}", $~[:pattern] argument = "=[#{argument[1..-1]}]" if style.include? :OPTIONAL pattern = pattern.gsub(/\//, '::').gsub(/(?:\A|[-_]+)\w/) { |p| p[-1].upcase } if pattern =~ /\A[-_a-z]/ pattern = OptionBinder.const_get(pattern) rescue Regexp.new(pattern) else argument.sub!(/\A(?:=\[|\[?=?)/, style.include?(:OPTIONAL) ? '=[' : '=') end end description = !string.empty? ? string.strip : nil return (style + [pattern, values] + shorts + longs + [argument, description]).compact, handler end