Method: Conify::Command#find_command

Defined in:
lib/conify/command.rb

#find_command(cmd, args = []) ⇒ Object

Finds file/method for command



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/conify/command.rb', line 14

def find_command(cmd, args = [])
  @current_cmd = cmd
  @current_args = args

  respond_with_help if seeking_help?
  respond_with_version if seeking_version?

  # Separate out primary/secondary commands based on if command was namespaced
  # e.g. `conify services vs. conify services:add`
  primary_cmd, secondary_cmd = @current_cmd.split(':')

  # Get the command file path (string) for the primary command
  primary_cmd_file = file_for_command(primary_cmd)

  # If the primary command has it's own file, require it
  primary_cmd_file_exists = File.exists?(primary_cmd_file)
  require primary_cmd_file if primary_cmd_file_exists

  # If a secondary command exists, the primary_cmd_file must be where our command method lies
  if !secondary_cmd.nil?
    error_no_command if !primary_cmd_file_exists

    # Get command_klass for file path. Example response --> Conify::Command::Services
    command_klass = klass_for_file(primary_cmd_file)

    # Error out if the command klass doesn't have a method named <secondary_cmd>
    error_no_command if !klass_has_method?(command_klass, secondary_cmd)

    run(command_klass, secondary_cmd)

  # If there's no secondary command, there are 2 options for where the command method could be (in order of priority):
  # (1) Inside the primary command file as the 'index' method
  # (2) Inside the global command file, as a method named <primary_cmd>
  else
    # Store lambda for later
    try_global = lambda {
      require 'conify/command/global'
      command_klass = Conify::Command::Global
      error_no_command if !klass_has_method?(command_klass, primary_cmd)
      run(command_klass, primary_cmd)
    }

    # Number 1 above. If primary_cmd file exists, call the index method on it if it exists.
    # If index method doens't exist, check to see if method is a global command.
    if primary_cmd_file_exists
      # Get command_klass for file path. Example response --> Conify::Command::Services
      command_klass = klass_for_file(primary_cmd_file)

      klass_has_method?(command_klass, 'index') ? run(command_klass, 'index') : try_global.call

    # Number 2 above. Check to see if method is a global command inside command/global.rb
    else
      try_global.call
    end
  end
end