如何将我的 rails 自定义生成器附加到模型一?

How do I attach my rails custom generator to the model one?

目前,我创建了一个独立的生成器。当我 运行 rails g query 时,它可以正常工作并很好地创建我的文件。

这里是代码:

# lib/generators/rails/query_generator.rb

require_relative '../my_lib/named_base'

module Rails
  module Generators
    class QueryGenerator < MyLib::Generators::NamedBase
      source_root File.expand_path('templates', __dir__)

      check_class_collision suffix: 'Query'

      def create_model_query
        return if class_name.blank?

        template_file = File.join('app/queries', class_path, "#{file_name}_query.rb")
        template 'query.rb.erb', template_file
      end
    end
  end
end

现在,我想 运行 生成器当人们 运行 rails g model 但我无法实现。 我尝试覆盖生成器模型 class 并使用 hook_for 来调用它,但它不起作用。这里的代码:

# lib/generators/rails/model_generator.rb

require "rails/generators"
require "rails/generators/rails/model/model_generator"
require_relative './query_generator'

module Rails
  module Generators
    class ModelGenerator < ::Rails::Generators::ModelGenerator
      hook_for :orm, as: :model, in: :rails do |instance, model|
        instance.invoke Rails::Generators::QueryGenerator, [ instance.name ]
      end
    end
  end
end

希望你能帮助我。谢谢!

终于,我找到了解决办法!在 Railtie 的帮助下,我可以从 rails 模型生成器实现预期的行为挂钩。

# lib/my_gem.rb
require ...
require 'my_gem/railtie' if defined?(Rails)
 
# lib/my_gem/railtie.rb

require 'rails/railtie'

module ActiveModel
  class Railtie < Rails::Railtie
    generators do |app|
      Rails::Generators.configure! app.config.generators
      require_relative '../generators/model_generator'
    end
  end
end

# lib/generators/model_generator.rb

require 'rails/generators'
require 'rails/generators/rails/model/model_generator'
require_relative 'rails/query_generator'

module Rails
  module Generators
    class ModelGenerator
      hook_for :query, type: :boolean, default: true
    end
  end
end