Class: Cri::ArgumentList

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/cri/argument_list.rb

Overview

A list of arguments, which can be indexed using either a number or a symbol.

Defined Under Namespace

Classes: ArgumentCountMismatchError

Instance Method Summary collapse

Constructor Details

#initialize(raw_arguments, explicitly_no_params, param_defns) ⇒ ArgumentList

Returns a new instance of ArgumentList.



15
16
17
18
19
20
21
# File 'lib/cri/argument_list.rb', line 15

def initialize(raw_arguments, explicitly_no_params, param_defns)
  @raw_arguments = raw_arguments
  @explicitly_no_params = explicitly_no_params
  @param_defns = param_defns

  load
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/cri/argument_list.rb', line 41

def method_missing(sym, *args, &block)
  if @arguments_array.respond_to?(sym)
    @arguments_array.send(sym, *args, &block)
  else
    super
  end
end

Instance Method Details

#[](key) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/cri/argument_list.rb', line 23

def [](key)
  case key
  when Symbol
    @arguments_hash[key]
  when Integer
    @arguments_array[key]
  else
    raise ArgumentError, "argument lists can be indexed using a Symbol or an Integer, but not a #{key.class}"
  end
end

#eachObject



34
35
36
37
38
39
# File 'lib/cri/argument_list.rb', line 34

def each
  return to_enum(__method__) unless block_given?

  @arguments_array.each { |e| yield(e) }
  self
end

#loadObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/cri/argument_list.rb', line 53

def load
  @arguments_array = []
  @arguments_hash = {}

  arguments_array = @raw_arguments.reject { |a| a == '--' }.freeze

  if !@explicitly_no_params && @param_defns.empty?
    # No parameters defined; ignore
    @arguments_array = arguments_array
    return
  end

  if arguments_array.size != @param_defns.size
    raise ArgumentCountMismatchError.new(@param_defns.size, arguments_array.size)
  end

  arguments_array.zip(@param_defns).each do |(arg, param_defn)|
    arg = param_defn.transform ? param_defn.transform.call(arg) : arg
    @arguments_hash[param_defn.name.to_sym] = arg
    @arguments_array << arg
  end
end

#respond_to_missing?(sym, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/cri/argument_list.rb', line 49

def respond_to_missing?(sym, include_private = false)
  @arguments_array.respond_to?(sym) || super
end