commander-rb / commander

The complete solution for Ruby command-line executables
MIT License
822 stars 74 forks source link

Please provide an example on how to call another command from within a command's block #100

Closed helge000 closed 3 years ago

helge000 commented 3 years ago

I couldn't feature out which method to call when I need to call a defind command from within another command's block. Example:

require 'commander/import'

program :name, 'Awsome'
program :version, '0.1'
program :description, 'A command'

command :'import-everything' do |c|
  c.action do |args, options|
    puts 'import!'
  end
end

command :'export-everything' do |c|
  c.action do |args, options|
    puts 'export!'
  end
end

command :'all' do |c|
  c.action do |args, options
    # Results in endless loop
    :'import-everything'.run! 
    :'export-everything'.run!
  end
end
ggilder commented 3 years ago

I don't think there's a reasonable way to do what you're describing. For starters, what should the arguments to the "inner" commands be? In some cases you might want the arguments that were passed to the outer command, but not in others.

In this situation I would really recommend decoupling your application code from the commander DSL — structure your code within its own class or module and call those methods from your commander commands.

class MyApp
  # call these from your commander commands like `MyApp.new.import_everything`
  def import_everything
  end

  def export_everything
  end
end