lib/ronin/ui/command_line/param_parser.rb in ronin-0.2.0 vs lib/ronin/ui/command_line/param_parser.rb in ronin-0.2.1
- old
+ new
@@ -25,49 +25,69 @@
module Ronin
module UI
module CommandLine
module ParamParser
- # Hash of format patterns and their parsers
- FORMATS = {
- /^[0-9]+$/ => lambda { |value| value.to_i },
- /^0x[0-9a-fA-F]+$/ => lambda { |value| value.hex },
- /^[a-zA-Z][a-zA-Z0-9]*:\/\// => lambda { |value| URI(value) },
- 'true' => lambda { |value| true },
- 'false' => lambda { |value| false }
- }
-
# The params Hash
attr_reader :params
#
- # Creates an empty +params+ Hash.
+ # The Array of parameter patterns and their parsers.
#
- def initialize
- @params = {}
+ def ParamParser.formats
+ @@ronin_param_formats ||= []
end
#
+ # Itereates over each parameter pattern and parser, passing them to the
+ # specified _block_.
+ #
+ def ParamParser.each_format(&block)
+ ParamParser.formats.each do |format|
+ block.call(format[:pattern],format[:parser])
+ end
+ end
+
+ #
+ # Adds a new parameter _pattern_ using the specified _block_ as the parser.
+ #
+ def ParamParser.recognize(pattern,&block)
+ ParamParser.formats.unshift({
+ :pattern => pattern,
+ :parser => block
+ })
+ end
+
+ protected
+
+ #
# Parses the specified _name_and_value_ string of the form
# "name=value" and extracts both the _name_ and the _value_, saving
# both the _name_ and _value_ within the +params+ Hash. If the
# extracted _value_ matches one of the patterns within +FORMATS+,
# then the associated parser will first parse the _value_.
#
def parse_param(name_and_value)
name, value = name_and_value.split('=',2)
if value
- FORMATS.each do |pattern,parser|
+ ParamParser.each_format do |pattern,parser|
if value.match(pattern)
value = parser.call(value)
break
end
end
end
- @params[name.to_sym] = value
+ return {name.to_sym => value}
end
+
+ ParamParser.recognize(/^[a-zA-Z][a-zA-Z0-9]*:\/\//) { |value| URI(value) }
+ ParamParser.recognize('false') { |value| false }
+ ParamParser.recognize('true') { |value| true }
+ ParamParser.recognize(/^0x[0-9a-fA-F]+$/) { |value| value.hex }
+ ParamParser.recognize(/^[0-9]+$/) { |value| value.to_i }
+
end
end
end
end