简体   繁体   English

如何在 Rails 生成器中使用 Thor::Shell::Basic?

[英]How to use Thor::Shell::Basic in a Rails Generator?

I am writing a Rails 3.2 generator and would like to use Thor::Shell::Basic instance methods (eg ask or yes? ) like they do in the official Rails guides on Application Templates .我正在编写一个 Rails 3.2 生成器,并希望使用Thor::Shell::Basic实例方法(例如ask还是yes? ),就像他们在应用程序模板官方 Rails 指南中所做的那样。

module MyNamespace
  class ScaffoldGenerator < Rails::Generators::Base
    source_root File.expand_path('../templates', __FILE__)

    if yes? "Install MyGem?"
      gem 'my_gem'
    end

    run 'bundle install'
  end
end

This will give me a NoMethodError: undefined method 'yes?' for MyNamespace::ScaffoldGenerator:Class这会给我一个NoMethodError: undefined method 'yes?' for MyNamespace::ScaffoldGenerator:Class NoMethodError: undefined method 'yes?' for MyNamespace::ScaffoldGenerator:Class . NoMethodError: undefined method 'yes?' for MyNamespace::ScaffoldGenerator:Class

I cannot figure out a clean way to make those instance methods available - I am already inheriting from Rails::Generators::Base .我想不出一种干净的方法来使这些实例方法可用 - 我已经从Rails::Generators::Base继承。

Edit:编辑:

Ah, it probably has nothing to do with Thor... I get a warning:啊,它可能与托尔无关......我收到警告:

[WARNING] Could not load generator "generators/my_namespace/scaffold/scaffold_generator"

Something is not set up correctly although I used the generator for generating generators...尽管我使用生成器生成生成器,但某些设置不正确...

Oh, yes, it does have to do something with Thor.哦,是的,它确实与托尔有关系。

Do not let yourself get confused by the warning.不要让自己对警告感到困惑。 You know that Rails::Generators uses Thor, so walk over to the Thor Wiki and check out how Thor tasks work .您知道 Rails::Generators 使用 Thor,因此请访问Thor Wiki并查看Thor 任务如何工作的

The rails generator execution will call any method in your generator. rails 生成器执行将调用生成器中的任何方法。 So make sure that you organize your stuff into methods:因此,请确保将您的内容组织成方法:

module MyNamespace
  class ScaffoldGenerator < Rails::Generators::Base
    source_root File.expand_path('../templates', __FILE__)

    def install_my_gem
      if yes? "Install MyGem?"
        gem 'my_gem'
      end
    end

    def bundle
      run 'bundle install'
    end
  end
end

Be sure to put your generator into the right folder structure, eg lib/generators/my_namespace/scaffold_generator.rb .确保将您的生成器放入正确的文件夹结构中,例如lib/generators/my_namespace/scaffold_generator.rb

Thanks for asking your question, dude!谢谢你的问题,伙计!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM