lib/args_parser/parser.rb in args_parser-0.0.5 vs lib/args_parser/parser.rb in args_parser-0.0.6
- old
+ new
@@ -1,9 +1,12 @@
module ArgsParser
- def self.parse(argv=[], &block)
- parser = Parser.new(&block)
+ def self.parse(argv=[], config={}, &block)
+ Config.default.each do |k,v|
+ config[k] = v unless config[k]
+ end
+ parser = Parser.new(config, &block)
parser.parse argv
parser
end
class Parser
@@ -26,11 +29,12 @@
def aliases
@aliases ||= Hash.new
end
public
- def initialize(&block)
+ def initialize(config, &block)
+ @config = config
unless block_given?
raise ArgumentError, 'initialize block was not given'
end
@filter = Filter.new
@validator = Validator.new
@@ -66,37 +70,18 @@
def args
params.keys
end
def parse(argv)
- k = nil
- argv.each_with_index do |arg, index|
- unless k
- if arg =~ /^-+[^-\s]+$/
- k = arg.scan(/^-+([^-\s]+)$/)[0][0].strip.to_sym
- k = aliases[k] if aliases[k]
- elsif index == 0
- @first = arg
- end
- else
- if arg =~ /^-+[^-\s]+$/
- params[k][:value] = true
- k = arg.scan(/^-+([^-\s]+)$/)[0][0].strip.to_sym
- k = aliases[k] if aliases[k]
- else
- arg = @filter.filter k, arg
- msg = @validator.validate k, arg
- if msg
- STDERR.puts "Error: #{msg} (--#{k} #{arg})"
- exit 1
- end
- params[k][:value] = arg
- k = nil
- end
+ method("parse_style_#{@config[:style]}".to_sym).call(argv)
+ params.each do |name, param|
+ next if [nil, true].include? param[:value]
+ param[:value] = @filter.filter name, param[:value]
+ msg = @validator.validate name, param[:value]
+ if msg
+ STDERR.puts "Error: #{msg} (--#{name} #{param[:value]})"
+ exit 1
end
- end
- if k
- params[k][:value] = true
end
end
def [](key)
params[key][:value] || params[key][:default]