Module: Loops::CLI::Commands::ClassMethods

Defined in:
lib/loops/cli/commands.rb

Instance Method Summary collapse

Instance Method Details

#[](command_name) ⇒ Command?

Return the registered command from the command name.

Parameters:

  • command_name (Symbol, String)

    a command name to register.

Returns:

  • (Command, nil)

    an instance of requested command.



48
49
50
51
# File 'lib/loops/cli/commands.rb', line 48

def [](command_name)
  command_name = command_name.to_sym
  @@commands[command_name] ||= load_and_instantiate(command_name)
end

#command_namesArray<String>

Get a list of command names.

Returns:

  • (Array<String>)

    an Array of command names.



37
38
39
# File 'lib/loops/cli/commands.rb', line 37

def command_names
  @@commands.keys.map { |c| c.to_s }
end

#executeObject

Parse arguments, find and execute command requested.



18
19
20
# File 'lib/loops/cli/commands.rb', line 18

def execute
  parse(ARGV).run!
end

#load_and_instantiate(command_name) ⇒ Command?

Load and instantiate a given command.

Parameters:

  • command_name (Symbol, String)

    a command name to register.

Returns:

  • (Command, nil)

    an instantiated command or nil, when command is not found.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/loops/cli/commands.rb', line 60

def load_and_instantiate(command_name)
  command_name = command_name.to_s
  retried = false

  begin
    const_name = command_name.capitalize.gsub(/_(.)/) { $1.upcase }
    Loops::Commands.const_get("#{const_name}Command").new
  rescue NameError
    if retried then
      nil
    else
      retried = true
      require File.join(Loops::LIB_ROOT, 'loops/commands', "#{command_name}_command")
      retry
    end
  end
end

#register_command(command_name) ⇒ Object

Register a Loops command.

Parameters:

  • command_name (Symbol, String)

    a command name to register.



27
28
29
30
# File 'lib/loops/cli/commands.rb', line 27

def register_command(command_name)
  @@commands ||= {}
  @@commands[command_name.to_sym] = nil
end