Class: ParseArgv::Result::Value

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/parse-argv.rb

Overview

This is a helper class to get parsed arguments from ParseArgv::Result to be converted.

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#valueObject (readonly)

Returns the argument value.

Returns:

  • (Object)

    the argument value



194
195
196
# File 'lib/parse-argv.rb', line 194

def value
  @value
end

#value?Boolean (readonly)

Returns whenever the value is nil and not false.

Returns:

  • (Boolean)

    whenever the value is nil and not false



206
207
208
# File 'lib/parse-argv.rb', line 206

def value?
  @value != nil && @value != false
end

Instance Method Details

#as(type, *args, default: nil, **kwargs) ⇒ Object

Requests the value to be converted to a specified +type+. It uses Conversion.[] to obtain the conversion procedure.

Some conversion procedures allow additional parameters which will be forwarded.

Examples:

convert to a positive number (or fallback to 10)

sample.as(:integer, :positive, default: 10)

convert to a file name of an existing, readable file

sample.as(File, :readable)

convert to Time and use the +reference+ to complete the the date parts (when not given)

sample.as(Time, reference: Date.new(2022, 1, 2))

Parameters:

  • type (Symbol, Class, Enumerable<String>, Array(type), Regexp)

    conversion type, see Conversion.[]

  • args (Array<Object>)

    optional arguments to be forwarded to the conversion procedure

  • default (Object) (defaults to: nil)

    returned, when an argument was not specified

  • kwargs (Symbol => Object)

    optional named arguments forwarded to the conversion procedure

Returns:

  • (Object)

    converted argument or +default+

See Also:



236
237
238
239
240
241
242
243
244
245
246
# File 'lib/parse-argv.rb', line 236

def as(type, *args, default: nil, **kwargs)
  return default if @value.nil?
  conv = Conversion[type]
  if value.is_a?(Array)
    value.map { |v| conv.call(v, *args, **kwargs, &@error_proc) }
  else
    conv.call(@value, *args, **kwargs, &@error_proc)
  end
rescue Error => e
  ParseArgv.on_error&.call(e) or raise
end