How to make two thor tasks share options?

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

    So there is a nice dry way to do this now, but may not fall into the requirements of being as idiomatic, though I wanted to mention it for anyone looking for a more recent answer.

    You can start by using the class_options to set the majority of shared options between your methods:

    module MyModule
      class Hello < Thor
        class_option :name, :desc => "name", :required => true
        class_option :greet, :desc => "greeting to use", :required => true
    
        desc "Hello", "Saying hello"
        def say
          puts "#{options[:greet]}, #{options[:name]}!"
        end
    
        desc "Say", "Saying anything"
        remove_class_option :greet
        def hello
          puts "Hello, #{options[:name]}!"
        end
    
        def foo
          puts "Foo, #{options[:name]}!"
        end
      end
    end
    

    The best part about this, is that it pertains to all methods after the declaration. With these set to required, you can see that the first method requires both greet and name, but say and foo only require the name.

提交回复
热议问题