How to make two thor tasks share options?

前端 未结 5 1320
予麋鹿
予麋鹿 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:05

    So as not to type "shared_options" all the time, you can also do this:

    require 'thor'
    
    class Cli < Thor
      class << self
        private
        def shared_options!
          # list your shared options here
          method_option :opt1, type: :boolean
          method_option :opt2, type: :numeric
          # etc
        end
    
        # alias original desc so we can call it from inside new desc
        alias_method :orig_desc, :desc
    
        # redefine desc, calling original desc, and then applying shared_options!
        def desc(*args)
          orig_desc(*args)
          shared_options!
        end
      end
    
      desc 'task1', 'Task 1'
    
      def task1
      end
    
      desc 'task2', 'Task 2'
    
      def task2
      end
    
      desc 'task3', 'Task 3'
    
      def task3
      end
    end
    

    Or if you don't want acrobatics with method aliasing, you could just define your own method "my_desc" and call that instead of "desc".

提交回复
热议问题