denisdefreyne / cri

A tool for building commandline applications
MIT License
120 stars 19 forks source link

Pass an arbitrary set of parameters to command definition #81

Closed anibalrojas closed 6 years ago

anibalrojas commented 6 years ago

I am trying to build a set of subcommands in a kind of modular way, something like:

class Whatever

    def initialize
      @root = self.class.root
      @root.add_command(self.class.subcommand)
    end

    def config
      @root
    end

    private

    def self.root`
      subcommand = Cri::Command.define do
         ...
      end 
      subcommand
   end

    def self.subcommand`
      subcommand = Cri::Command.define do
         ...
      end 
      subcommand
   end

end

I would like to do some initializations in the main class and pass parameters to the methods to make them available to the command definitions. Cri::Command.define could use an additional parameter (it has three now) that is an arbitrary hash. Not sure if this is the intended usage, or maybe I am missing a pattern to build a subcommand set in a modular fashion.

denisdefreyne commented 6 years ago

The block given to Cri::Command.define has access to the scope around it, so you can pass data to it:

short_opt = 'f'
long_opt = 'force'
opt_desc = 'enable force mode'

command = Cri::Command.define do
  name 'push'
  usage 'push [options]'
  summary 'Push data to the server'

  option short_opt, long_opt, opt_desc
end

puts command.help
NAME
    push - Push data to the server

USAGE
    push [options]

OPTIONS
    -f --force      enable force mode
anibalrojas commented 6 years ago

Indeed, it is just a block with access to the context where it is defined, I was getting overly complicated. Thanks.