rubygem thor的使用

Thor 是 Rails 3 以后内建的命令行工具,严格意义上说,Thor 不仅仅用于解析命令行参数,而是用于替代 rake 作为新的 task 标准工具,Thor 的命令行参数解能是自己实现的,我个人建议在写 Rails 的 task 的时候,把 Thor 作为首选,但是作一般用途的命令行工具,Thor有点 overkill 了。

简单示例:

文件 entrypoint.rb

#!/usr/bin/env ruby
require 'thor'
class Ctrol  < Thor
  desc "hello NAME","puts name"
  def hello
    puts "name"
  end
end
Ctrol.start()

运行命令:

ruby entrypoint.rb

运行结果:

Commands:
  entrypoint_1.rb hello NAME      # puts name     # =>解释: hello NAME 为desc描述的第一个字符串, # puts name 为desc描述的第二个字符串;
  entrypoint_1.rb help [COMMAND]  # Describe available commands or one specific command # => 默认显示

运行命令:ruby entrypoint.rb testfunc #解释:testfunc并没有定义,会显示如下:

caofengzhen@chef-workstation:~/caofz/thor$ ruby entrypoint.rb testfunc
Could not find command "testfunc".

运行命令:

ruby entrypoint.rb hel #解释:testfunc并没有定义会提示补全方法,显示如下:

caofengzhen@chef-workstation:~/caofz/thor$ ruby entrypoint1.rb hel
Ambiguous command hel matches [hello, help]

运行命令:ruby entrypoint1.rb hello 会执行hello方法的block,打印出"name"

caofengzhen@chef-workstation:~/caofz/thor$ ruby entrypoint1.rb hello
name

 

posted @ 2015-12-28 15:24  caofz  阅读(368)  评论(0)    收藏  举报