Sha256: 5f949725eff11d24a039018c75400cc2c5400583cb18a68216a3cb68dc250438

Contents?: true

Size: 1.32 KB

Versions: 4

Compression:

Stored size: 1.32 KB

Contents

# Abstract class with definitions of commands
class Command
  def self.options_messages
    raise 'return a list with how to use this command'
  end

  def self.command_name
    raise 'return the command name'
  end

  def self.run(argv)
    run_childrens(argv)
  end

  def self.parent
    raise 'return the parent command'
  end

  def self.childrens
    raise 'return the childrens commands'
  end

  def self.childrens?
    !childrens.empty?
  end

  def self.run_childrens(argv)
    children_command = argv.first
    children = childrens.detect { |c| c.command_name == children_command }
    return usage unless children

    argv.delete(children.command_name)
    children.run(argv)
  end

  def self.usage
    usage_message = usage_header
    usage_message += "\n\n[options]\n"

    childrens.each do |command|
      messages = command.options_messages
      messages = [messages] unless messages.is_a?(Array)

      messages.each do |message|
        usage_message += "\n#{message}" if message
      end
    end

    puts usage_message
  end

  def self.usage_header
    header = ''
    header += '[option]' if childrens?
    header = "#{command_name} " + header

    parent = self.parent
    until parent.nil?
      header = "#{parent.command_name} " + header
      parent = parent.parent
    end

    header = '$ ' + header
    header
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
lookfile-0.1.3 lib/command.rb
lookfile-0.1.2 lib/command.rb
lookfile-0.1.1 lib/command.rb
lookfile-0.1.0 lib/command.rb