Class: KXI::CLI::ArgumentValues

Inherits:
Object
  • Object
show all
Defined in:
lib/kxi/cli/argument_values.rb

Overview

Manages values of arguments

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ ArgumentValues

Instantiates the KXI::CLI::ArgumentValues class

Parameters:



9
10
11
12
13
14
15
16
17
# File 'lib/kxi/cli/argument_values.rb', line 9

def initialize(args)
	@args = args
	@vals = {}
	args.each do |a|
		if a.is_a?(KXI::CLI::FlagArgument)
			@vals[a.name] = { :argument => a, :value => false }
		end
	end
end

Instance Method Details

#[](index) ⇒ String

Gets value of argument

Parameters:

Returns:

  • (String)

    Value of argument

Raises:

  • (Exception)


45
46
47
48
49
50
51
52
53
# File 'lib/kxi/cli/argument_values.rb', line 45

def [](index)
	if index.is_a?(Symbol)
		index = index.to_s
	elsif index.is_a?(KXI::CLI::Argument)
		index = index.name
	end
	raise(Exception.new("Undefined argument '#{index}'!")) unless @vals.include?(index)
	return @vals[index][:value]
end

#finishObject

Validates variadic arguments and checks for minimal argument requirements



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/kxi/cli/argument_values.rb', line 66

def finish
	@args.each do |arg|
		if @vals.include?(arg.name)
			unless arg.is_a?(KXI::CLI::FlagArgument)
				begin
					arg.validate(@vals[arg.name][:value])
				rescue Exception => ex
					raise(KXI::Exceptions::ArgumentException.new(arg.name, ex.message))
				end
			end
		else
			raise(KXI::Exceptions::ArgumentException.new(arg.name, 'Argument is mandatory!')) if arg.required?
			@vals[arg.name] = { :argument => arg, :value => arg.default }
		end
	end
end

#set(arg, val) ⇒ Object

Assigns (or adds) a value to argument

Parameters:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/kxi/cli/argument_values.rb', line 22

def set(arg, val)
	if arg.is_a?(KXI::CLI::FlagArgument)
		raise(KXI::Exceptions::ArgumentException.new(arg.name, 'Flag set multiple times!')) if @vals[arg.name][:value]
		@vals[arg.name][:value] = val
	else
		if arg.variadic?
			@vals[arg.name] = { :argument => arg, :value => [] } if @vals[arg.name] == nil
			@vals[arg.name][:value].push(val)
		else
			raise(KXI::Exceptions::ArgumentException.new(arg.name, 'Argument set multiple times!')) if @vals[arg.name] != nil
			begin
				arg.validate(val)
			rescue Exception => ex
				raise(KXI::Exceptions::ArgumentException.new(arg.name, ex.message))
			end
			@vals[arg.name] = { :argument => arg, :value => val }
		end
	end
end

#to_hHash

Converts class to hash

Returns:

  • (Hash)

    Equivalent hash



57
58
59
60
61
62
63
# File 'lib/kxi/cli/argument_values.rb', line 57

def to_h
	ret = {}
	@vals.each_pair do |k, v|
		ret[k] = v[:value]
	end
	return ret
end