Akash
Akash

Reputation: 5231

Commands in ruby terminal application

I have just written my first terminal application in ruby. I use OptionParser to parse the options and their arguments. However I want to create commands. For example:

git add .

In the above line, add is the command which cannot occur anywhere else than immediately after the application. How do I create these.

I will appreciate if anyone could point me in the right direction. However, please do not reference any gems such as Commander. I already know about these. I want to understand how it is done.

Upvotes: 0

Views: 228

Answers (2)

DMKE
DMKE

Reputation: 4603

The OptionParser's parse! takes an array of arguments. By default, it will take ARGV, but you can override this behaviour like so:

Basic Approach

def build_option_parser(command)
  # depending on `command`, build your parser
  OptionParser.new do |opt|
    # ...
  end
end

args = ARGV
command = args.shift # pick and remove the first option, do some validation...
@options = build_option_parser(command).parse!(args) # parse the rest of it

Advanced Approach

Instead of a build_option_parser method with a huge case-statement, consider an OO approach:

class AddCommand
  attr_reader :options
  def initialize(args)
    @options = {}
    @parser = OptionParser.new #...
    @parser.parse(args)
  end
end

class MyOptionParser
  def initialize(command, args)
    @parser = {
      'add' => AddCommand,
      '...' => DotsCommand
    }[command.to_s].new(args)
  end
  def options
    @parser.options
  end
end

Alternatives

For sure, there exist tons of Rubygems (well, 20 in that list), which will take care of your problem. I'd like to mention Thor which powers, e.g. the rails command line tool.

Upvotes: 2

philant
philant

Reputation: 35856

You can retrieve the command with Array#shift prior invoking OptionParser.

Upvotes: 0

Related Questions