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



20
21
22
23
24
25
26
# File 'lib/cri/argument_list.rb', line 20

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



44
45
46
47
48
49
50
# File 'lib/cri/argument_list.rb', line 44

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



28
29
30
31
32
33
34
35
36
37
# File 'lib/cri/argument_list.rb', line 28

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



39
40
41
42
# File 'lib/cri/argument_list.rb', line 39

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

#loadObject



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

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)


52
53
54
# File 'lib/cri/argument_list.rb', line 52

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