【问题标题】:Adding a --version option to a Ruby Thor CLI向 Ruby Thor CLI 添加 --version 选项
【发布时间】:2014-04-02 11:28:53
【问题描述】:

如何将--version 选项添加到我的Ruby Thor 命令行界面应用程序。

例如我希望能够运行

$ thor_app --version
> thor_app version 1.0.0

这个问题与Run a CLI Thor app without arguments or task name有关,但专门添加一个不需要任务的--version选项。

注意
这是在self-answer format 之后编写的。鼓励添加答案和更新

【问题讨论】:

    标签: ruby thor


    【解决方案1】:

    我对这种方法有点运气:

    class CLI < Thor
      map %w[--version -v] => :__print_version
    
      desc "--version, -v", "print the version"
      def __print_version
        puts FooBar::VERSION
      end
    end
    

    前导下划线确保没有像yourapp version 这样的命令,并强制使用yourapp --versionyourapp -vdesc 内容将允许它显示为 -v, --version 而不会暴露 __print_version

    【讨论】:

    • 这就是 bundler 所做的。只有他们只是调用任务版本并让人们也用bundler version 调用它(因为为什么不呢?)github.com/bundler/bundler/blob/…
    • 这应该提交给 Thor 开发人员进行文档修复。
    • 请注意,您必须重新安装 gem 才能获得新的操作。如果要动态测试,可以运行:bundle exec bin/gem_name
    【解决方案2】:

    我不喜欢公认的解决方案;它最终将version 列为命令,将--version--no-version 列为全局选项,如果脚本在没有选项的情况下运行,它会保持沉默而不是提供帮助。

    我能想到的最好的办法就是在 Thor 之外做:

    class CLI < Thor
       .
       .
       .
    end
    
    if ARGV[0] == "--version"
        puts "MyApp #{MyApp::VERSION}"
        exit
    end
    
    CLI.start
    

    这有个小缺点,--version 没有在任何地方记录。

    【讨论】:

    【解决方案3】:

    到目前为止我想出的最好的选择是创建一个布尔类选项,它不属于一个任务,可以被其他任务引用。类选项的常用示例是-vverbose,因为所有任务都可以使用它来确定它们应该有多嘈杂。

    然后创建一个“版本”任务并将其设置为默认任务,因此当没有定义任务时,版本任务将运行并可以对 --version 标志(类选项)做出反应。

    class CLI < Thor
      #include Thor::Actions
      class_option :version, :type => :boolean
    
      desc "version", "Show thor_app version"
      def version
        if options[:version]
          puts "thor_app version #{find_version}"
        end
      end
      default_task :version
    
      no_tasks do
        def find_version
          ## Method can be replaced to look up VERSION
          '1.0.0'
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多