I had the same problem, and I used what N.N. answered. But I found some problems:
If you want to share more than one option, as in the example, it does not work very well. Imagine what you want to share :value between task2 and task3. You can create another shared_options or create an array with shared parameters and access it with the name shared_option.
It works, but it is verbose and hard to read. I implemented something small to be able to exchange options.
Cli < Thor class << self def add_shared_option(name, options = {}) @shared_options = {} if @shared_options.nil? @shared_options[name] = options end def shared_options(*option_names) option_names.each do |option_name| opt = @shared_options[option_name] raise "Tried to access shared option '#{option_name}' but it was not previously defined" if opt.nil? option option_name, opt end end end
This creates a hash with the parameter name as the key, and โdefinitionโ (required, default, etc.) as the value (which is the hash). It is easily accessible after that.
With this, you can do the following:
require 'thor' class Cli < Thor add_shared_option :type, :type => :string, :required => true, :default => 'foo' add_shared_option :value, :type => :numeric desc 'task1', 'Task 1' shared_options :type def task1 end desc 'task2', 'Task 2' shared_options :type, :value def task2 end desc 'task3', 'Task 3' shared_options :value def task3 end end Cli.start(ARGV)
For me it looks more readable, and if the number of teams is more than 3 or 4, it will be a big improvement.
dgmora
source share