lib/samovar/options.rb in samovar-1.1.1 vs lib/samovar/options.rb in samovar-1.2.0
- old
+ new
@@ -20,11 +20,11 @@
require_relative 'flags'
module Samovar
class Option
- def initialize(flags, description, key: nil, default: nil, value: nil)
+ def initialize(flags, description, key: nil, default: nil, value: nil, type: nil, &block)
@flags = Flags.new(flags)
@description = description
if key
@key = key
@@ -34,23 +34,33 @@
@default = default
@value = value
@value ||= true if @flags.boolean?
+
+ @type = block_given? ? block : type
end
attr :flags
attr :description
attr :type
attr :default
attr :key
+ def coerce(result)
+ if @type
+ @type.call(result)
+ else
+ result
+ end
+ end
+
def parse(input)
if result = @flags.parse(input)
- @value.nil? ? result : @value
+ @value.nil? ? coerce(result) : @value
else
@default
end
end
@@ -89,11 +99,11 @@
end
attr :key
attr :defaults
- def option(*args, **options)
- self << Option.new(*args, **options)
+ def option(*args, **options, &block)
+ self << Option.new(*args, **options, &block)
end
def << option
@ordered << option
option.flags.each do |flag|