【问题标题】:How to use thor in rails?如何在rails中使用thor?
【发布时间】:2015-09-10 01:56:46
【问题描述】:

Thor 是一个用于构建强大的命令行界面的工具包。

它总是用于单个命令行。如果我想在 Rails 项目中使用它,例如:

lib/tasks/my_cli.rb

require "thor"

class MyCLI < Thor
  desc "hello NAME", "say hello to NAME"
  def hello(name)
    puts "Hello #{name}"
  end
end

MyCLI.start(ARGV) 放在哪里?

如果我把它放在那个文件下(lib/tasks/my_cli.rb),当我运行我的 rspec 测试时,它会显示命令消息:

Commands:
  rspec help [COMMAND]   # Describe available commands or one specific command
  rspec hello NAME       # say hello to NAME

我不想在我的bundle exec rspec 中看到它,所以我将MyCLI.start(ARGV) 移动到bin/rails。看起来不错。但是在我这样做之后:

$ ./bin/rails s -b 0.0.0.0
$ [CTRL+C]

我看到了这条消息:

=> 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".

什么意思:

Could not find command "_b".

所以,我不知道如何在 Rails 项目中使用 thor 的最佳实践。

【问题讨论】:

  • 我认为它可能会将您发送到 Rails 服务器的 -b 传递给 thor。我很好奇这里的用例是什么。为什么要在 Rails 项目中使用 thor?肯定有一种方法可以做您正在寻找的事情,如果有一些关于这里动机的背景知识会很好。
  • @fdisk 谢谢。我必须使用一些选项手动运行批处理。所以我使用了thor。还有其他方法可以做某事吗?
  • 您也可以使用rake 来启动lib/tasks 中定义的任务,这是我在大多数Rails 商店中看到的。
  • 如果使用rake,可以选择吗?

标签: ruby-on-rails ruby command-line rspec thor


【解决方案1】:

你必须使用method_option: https://github.com/erikhuda/thor/wiki/Method-Options

并且不要像普通方法一样传递参数

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

然后将其与thor 命令一起使用: thor mycli:hello -b Robert

【讨论】:

  • 非常感谢。我在课堂外添加了一个模块。所以当我运行雷神命令thor Tasks::MyCLI:hello -b any时,它说:Could not find command "Tasks::MyCLI:hello
  • thor tasks:mycli:hello -b Robert 像这样使用它s-cho-m 并检查响应是否有用,如果它有用,请检查
  • 我正在考虑在我的 rails 应用程序中弃用我所有的自定义 rake 任务以支持 Thor。我会在我的 Rails 应用程序中的哪个位置放置这样的文件,以便 thor 自动找到命令?在许多情况下,我希望将 rails 环境加载到 Thor 任务上下文中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-11
  • 2011-02-08
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
相关资源
最近更新 更多