Class: Caty::Option

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/caty/option.rb

Overview

Represents a single option.

An Option object is created for every option specified via Caty#task_options(). The sum of all options parsed is accessible via the Caty#task_options() method.

Direct Known Subclasses

GlobalOption

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, default) ⇒ Option

Creates a new option with the given name and default value.

default may be one of the following:

  • :boolean nil is the default, any given argument will be coerced into a boolean value.

  • :string nil is the default, any given argument will be coerced into a string value.

  • :integer nil is the default, any given argument will be coerced into a integer value.

  • an Integer, String or Boolean value the passed value is the default value, any given argument will be coerced into the given type.

  • any other value will be treated as if a String had been given.

If the deduced argument type is boolean, not giving an argument on the command line is interpreted as giving ‘true’ as the argument. For all the other types, a MissingOptionArgumentError is thrown.

Raises:

  • (ArgumentError)


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/caty/option.rb', line 42

def initialize( name, default )
    @name       = name
    @converter  = nil

    Caty::Converter.types.each do |type,converter|
        if default == type
            @converter   = converter.new
            @default     = nil
            break
        elsif converter.allowed_defaults.any? { |klass| default.is_a?(klass) }
            @converter   = converter.new
            @default     = default
            break
        end
    end

    raise(
        ArgumentError,
        'Only boolean, string and integer values or :boolean, :integer, :string allowed.'
    ) if @converter.nil?
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



17
18
19
# File 'lib/caty/option.rb', line 17

def name
  @name
end

Instance Method Details

#grep!(args) ⇒ Object

Tries to remove the option from the args. Returns the value grepped for this option.



68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/caty/option.rb', line 68

def grep!( args )
    rex   = %r{^#{self.prefix}#{@name}(?:=(.+))?$}
    index = args.index { |arg| rex =~ arg }

    if index.nil?
        @default
    else
        match = rex.match(args.delete_at(index))
        @converter.convert(match[1])
    end
rescue Caty::OptionArgumentError  => e
    e.option = @name
    raise e
end

#to_sObject



83
84
85
86
87
# File 'lib/caty/option.rb', line 83

def to_s
    "[#{self.prefix}#{@name}=#{
        @default.nil? ? '' : @default.inspect
    }]"
end