ruby中Thor用法雷神介绍,MyCLI < Thor详细介绍

本文详细介绍了Ruby中的Thor库,用于构建强大的命令行接口。Thor被广泛用于如Bundler、Vagrant和Rails等项目。文章通过实例演示了如何将公共方法转化为命令、设置可选参数、定义命令描述、指定选项类型、需求选项、简写选项类型、类选项以及子命令的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者:小白蒋,个人博客:www.nihao070.cn

ruby中Thor是什么?

答:Thor是构建强大命令行接口的工具箱。Bundler, Vagrant, Rails以及其他的一些项目使用了Thor构建其命令行工具。bundler用来处理Ruby项目的版本依赖,Vagrant用来管理虚拟机运行环境,Rails是web开发框架。
Thor is a toolkit for building powerful command-line interfaces. It is used in Bundler, Vagrant, Rails and others.

第一点:公共方法变成命令

一个简单的Thor类公开带有许多子命令的可执行文件,比如git或bundler。在Thor类中,公共方法变成命令。
新建一个MyCLI.rb文件

  1 require "thor"
  2 
  3 class MyCLI < Thor
  4     desc "hello NAME", "say hello to NAME"
  5     def hello(name)
  6         puts "hi #{
     name}"
  7     end
  8 end
  9 
 10 MyCLI.start(ARGV)
~                           

在这里,你想执行,上面定义的hello方法就得在命令中输入,然后hello 命令后面在跟参数name

ruby MyCLI hello mary

输出:

hi Mary

第二点:你也可以使用Ruby的可选参数使CLI参数可选

  1 require "thor"
  2 
  3 class MyCLI < Thor
  4     desc "hello NAME", "say hello to NAME"
  5     def hello(name, from=nil)
  6         puts "from: #{
     from}" if from
  7         puts "hello #{
     name}"
  8     end
  9 end
 10 
 11 MyCLI.start(ARGV)                        

执行ruby MyCLI.rb hello mary bos, from参数如果不传递就是nil(空),如果传递就打印出from:bos

from: bos
hello mary

第三点:long_desc、\x5

①在许多情况下,您需要在较长的使用说明中提供较长的描述。在这种情况下,可以使用long_desc指定更长的使用指令。
②默认情况下,较长的描述以终端的大小包装行,并使用一个换行符将行分组在一起,就像Markdown一样。还可以在行首使用\x5转义序列强制行之间进行一次硬换行。**

  1 require "thor"
  2 
  3 class MyCLI < Thor
  4   desc "hello NAME", "say hello to NAME"
  5   long_desc <<-LONGDESC
  6     `cli hello` will print out a message to a person of your
  7     choosing.
  8 
  9     You can optionally specify a second parameter, which will print
 10     out a from message as well.
 11 
 12     > $ cli hello "Yehuda Katz" "Carl Lerche"
 13 
 14     \x5> from: Carl Lerche
 15   LONGDESC
 16   def hello(name, from=nil)
 17     puts "from: #{
     from}" if from
 18     puts "Hello #{
     name}"
 19   end
 20 end
 21 
 22 MyCLI.start(ARGV)     
 执行跟上面命令一样                     

第四点:thor可以更容易指定选项和标签作为元数据

Thor makes it easy to specify options and flags as metadata about a Thor command:

  1 require "thor"
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白蒋博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值