[英]How to use thor in rails?
Thor is a toolkit for building powerful command-line interfaces. Thor是用于构建强大的命令行界面的工具包。
It always been used for single command line. 它总是用于单个命令行。 If I want to use it in a rails project, for example:
如果我想在rails项目中使用它,例如:
lib/tasks/my_cli.rb LIB /任务/ my_cli.rb
require "thor"
class MyCLI < Thor
desc "hello NAME", "say hello to NAME"
def hello(name)
puts "Hello #{name}"
end
end
Where to put the MyCLI.start(ARGV)
? 放置
MyCLI.start(ARGV)
?
If I put it under that file( lib/tasks/my_cli.rb
), when I run my rspec test, it will show me the command message: 如果我将它放在该文件(
lib/tasks/my_cli.rb
)下,当我运行我的rspec测试时,它会显示命令消息:
Commands:
rspec help [COMMAND] # Describe available commands or one specific command
rspec hello NAME # say hello to NAME
I don't want to see it in my bundle exec rspec
, so I moved the MyCLI.start(ARGV)
to bin/rails
. 我不想在我的
bundle exec rspec
看到它,所以我将MyCLI.start(ARGV)
到bin/rails
。 It looks well. 它看起来很好。 But after I do this:
但在我这样做之后:
$ ./bin/rails s -b 0.0.0.0
$ [CTRL+C]
I saw this message: 我看到这个消息:
=> Booting Thin
=> Rails 4.2.0 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Thin web server (v1.6.3 codename Protein Powder)
Maximum connections set to 1024
Listening on 0.0.0.0:3000, CTRL+C to stop
^CStopping ...
Exiting
Could not find command "_b".
What does it mean: 这是什么意思:
Could not find command "_b".
So, I don't know a best practice about how to use thor in a rails project. 所以,我不知道如何在rails项目中使用thor的最佳实践。
You have to use method_option: https://github.com/erikhuda/thor/wiki/Method-Options 你必须使用method_option: https : //github.com/erikhuda/thor/wiki/Method-Options
And don't pass arguments like if it would be a normal method 并且不要传递参数,就好像它是一个普通的方法
require "thor"
class MyCLI < Thor
desc "hello NAME", "say hello to NAME"
method_option :name, aliases: '-b', type: :string, desc: 'It`s the named passed'
def hello
puts "Hello #{options[:name]}"
end
end
Then use it with thor
command: thor mycli:hello -b Robert
然后用
thor
命令使用它: thor mycli:hello -b Robert
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.