【问题标题】:How to use Thor::Shell::Basic in a Rails Generator?如何在 Rails 生成器中使用 Thor::Shell::Basic?
【发布时间】:2012-12-03 00:00:05
【问题描述】:

我正在编写 Rails 3.2 生成器,并希望像在 official Rails guides on Application Templates 中那样使用 Thor::Shell::Basic 实例方法(例如 askyes?)。

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

这会给我一个NoMethodError: undefined method 'yes?' for MyNamespace::ScaffoldGenerator:Class

我想不出一个干净的方法来使这些实例方法可用 - 我已经从 Rails::Generators::Base 继承。

编辑:

啊,这可能与托尔无关……我收到警告:

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

虽然我使用生成器来生成生成器,但有些东西设置不正确...

【问题讨论】:

    标签: ruby-on-rails ruby thor


    【解决方案1】:

    哦,是的,它确实与托尔有关。

    不要让自己对警告感到困惑。您知道 Rails::Generators 使用了 Thor,所以请前往 the Thor Wiki 并查看 how Thor tasks work

    rails 生成器执行将调用生成器中的任何方法。因此,请确保将内容组织成方法:

    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
    

    确保将您的生成器放入正确的文件夹结构中,例如lib/generators/my_namespace/scaffold_generator.rb.

    谢谢你的问题,伙计!

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 2011-05-23
      • 1970-01-01
      相关资源
      最近更新 更多