lib/rprogram/option.rb in rprogram-0.1.5 vs lib/rprogram/option.rb in rprogram-0.1.6
- old
+ new
@@ -1,7 +1,5 @@
-require 'rprogram/extensions'
-
module RProgram
class Option
# Flag of the option
attr_reader :flag
@@ -41,63 +39,65 @@
#
#
def initialize(options={},&block)
@flag = options[:flag]
- @equals = options[:equals] || false
- @multiple = options[:multiple] || false
- @separator = options[:separator]
- @sub_options = options[:sub_options] || false
+ @equals = (options[:equals] || false)
+ @multiple = (options[:multiple] || false)
+ @separator = if options[:separator]
+ options[:separator]
+ elsif options[:equals]
+ ' '
+ end
+ @sub_options = (options[:sub_options] || false)
- @formating = block
+ @formatter = if block
+ block
+ else
+ Proc.new do |opt,value|
+ if opt.equals
+ ["#{opt.flag}=#{value.first}"]
+ else
+ [opt.flag] + value
+ end
+ end
+ end
end
#
# Returns an +Array+ of the arguments for the option with the specified
# _value_.
#
def arguments(value)
- return [@flag] if value==true
- return [] if (value==nil || value==false)
+ return [@flag] if value == true
+ return [] unless value
- if value.respond_to?(:arguments)
- value = value.arguments
- end
+ value = value.arguments if value.respond_to?(:arguments)
- if @multiple
- if value.respond_to?(:map)
- return value.map { |arg| format(arg) }
- end
+ if value.kind_of?(Hash)
+ value = value.map { |key,sub_value|
+ if sub_value == true
+ key.to_s
+ elsif sub_value
+ "#{key}=#{sub_value}"
+ end
+ }
+ elsif value.kind_of?(Array)
+ value.flatten!
+ else
+ value = [value]
end
- if (value.kind_of?(Array) && @separator)
- value = value.join(@separator)
- end
+ value.compact!
- return format(value)
- end
-
- protected
-
- #
- # Returns an Array of the flag and the specified _value_ in argument
- # form.
- #
- def default_format(value)
- return [@flag] + value if value.kind_of?(Array)
- return ["#{flag}=#{value}"] if @equals
- return [@flag, value]
- end
-
- #
- # Formats specified _value_ with the option flag using
- # either the custom formating or the default_format.
- #
- def format(value)
- if @formating
- return @formating.call(@flag,value).to_a
+ if @multiple
+ return value.inject([]) do |args,value|
+ args + @formatter.call(self,[value])
+ end
else
- return default_format(value)
+ value = [value.join(@separator)] if @separator
+
+ return @formatter.call(self,value)
end
end
end
end