How to make two thor tasks share options?

前端 未结 5 1325
予麋鹿
予麋鹿 2021-02-14 04:37

With Thor one can use method_option to set the options for a particular task. To set the options for all tasks in a class one can use class_option. But what about t

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 05:08

    method_option is defined in thor.rb and it takes the following parameters according to the documentation:

    • name:: The name of the argument.
    • options:: Described below.

    Knowing this you can store the parameters to method_option in an array and expand that array into separate parameters as method_option is called.

    require 'thor'
    
    class Cli < Thor
      shared_options = [:type, {:type => :string, :required => true, :default => 'foo'}]
    
      desc 'task1', 'Task 1'
      method_option *shared_options
      def task1
      end
    
      desc 'task2', 'Task 2'
      method_option *shared_options
      method_option :value, :type => :numeric
      def task2
      end
    
      desc 'task3', 'Task 3'
      method_option :verbose, :type => :boolean, :aliases => '-v'
      def task3
      end
    end
    
    Cli.start(ARGV)
    

    I have no idea if this is idiomatic and I do not think it is that elegant. Still, it is better than violating the DRY principle.

提交回复
热议问题