【问题标题】:Generator not working in gem生成器在 gem 中不起作用
【发布时间】:2014-04-01 10:32:52
【问题描述】:

在 gem 中创建生成器时遇到问题。当我运行rails g 时,会显示生成器:

Supportator:
  supportator:initializer

但是当我使用rails generate supportator:initializer 运行生成器时,会出现以下错误:

Could not find generator supportator:initializer.

这是生成器的代码:

require 'rails/generators'

module Supportator
  class InitializerGenerator < Rails::Generators::Base
    source_root File.expand_path("../templates", __FILE__)

    def create_initializer_file
      copy_file '_browser_validator.html.haml', 'app/views/_browser_validator.html.haml'
      copy_file 'en_supportator.yml' , 'config/locales/en_supportator.yml'
      copy_file 'es_supportator.yml' , 'config/locales/es_supportator.yml'
    end

  end
end

这是引擎的代码:

module Supportator
  require 'rails'
  class Engine < ::Rails::Engine
  end
end

你知道为什么会这样吗?

【问题讨论】:

  • 您是否在lib/generators/ 目录中创建了生成器?
  • 生成器位于lib/generators/supportator/supportator_generator.rb

标签: ruby-on-rails ruby ruby-on-rails-4 generator rails-engines


【解决方案1】:

改变

lib/generators/supportator/supportator_generator.rb

lib/generators/supportator/initializer_generator.rb 

你的班级名称是InitializerGenerator,所以文件名应该是initializer_generator.rb。 否则,rails 将无法找到它。

在您使用 rails g supportator:initializer 的情况下,rails 会在 lib/generators/supportator 目录中查找生成器文件 initializer_generator.rb

【讨论】:

    【解决方案2】:

    问题在于文件的目录和名称。到以下生成器:

    require 'rails/generators'
    
    module Supportator
      module Generators
          class InstallGenerator < ::Rails::Generators::Base
            source_root File.expand_path("../../../templates", __FILE__)
    
            def create_initializer_file
              copy_file '_browser_validator.html.haml', 'app/views/_browser_validator.html.haml'
              copy_file 'en_supportator.yml' , 'config/locales/en_supportator.yml'
              copy_file 'es_supportator.yml' , 'config/locales/es_supportator.yml'
            end
    
          end
      end
    end
    

    目录和文件名应该是:

    /lib
      /generators
        /supportator
          /install
            /install_generator.rb
    

    【讨论】:

    • 您在此处发布的原始问题和答案不匹配。问题中没有module Generatorsclass InstallGenerator。我所有回答这个问题的努力都是徒劳的,因为现在你恢复了我接受的答案?
    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多