如何覆盖Rails的默认迁移生成器模板

时间:2014-08-07 15:34:36

标签: ruby-on-rails ruby-on-rails-3 activerecord rails-generators

我需要覆盖这些迁移模板:

https://github.com/rails/rails/blob/e20dd73df42d63b206d221e2258cc6dc7b1e6068/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb  和https://github.com/rails/rails/blob/e20dd73df42d63b206d221e2258cc6dc7b1e6068/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb

在我的rails应用程序中,以便他们从rails应用程序而不是gem本身获取模板。到目前为止,我已尝试过所有可能的组合,但没有运气。

我尝试过的事情:

- Rails.root/lib/templates/rails/migration/migration.rb
- Rails.root/lib/templates/rails/migration_generator/migration.rb
- Rails.root/lib/rails/templates/rails/migration/migration.rb
- Rails.root/lib/rails/templates/rails/migration_generator/migration.rb
- Rails.root/lib/rails/generators/templates/rails/migration/migration.rb
- Rails.root/lib/rails/generators/templates/rails/migration_generator/migration.rb
- Rails.root/lib/rails/templates/generators/rails/migration/migration.rb
- Rails.root/lib/rails/templates/generators/rails/migration_generator/migration.rb
- Rails.root/lib/rails/generators/active_record/migration/templates/migration.rb
- Rails.root/lib/rails/generators/active_record/migration_generator/templates/migration.rb
- Rails.root/lib/rails/generators/active_record/templates/migration.rb
- Rails.root/lib/rails/generators/active_record/templates/migration.rb

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:6)

我为我的案例找到了一个解决方法:

我使用此命令创建Rails生成器(在我的Rails应用程序目录中) -

rails g generator my_migrator

它创建:

lib/generators/my_migrator/my_migrator.rb
lib/generators/my_migrator/templates
lib/generators/my_migrator/USAGE

然后我添加了此代码,通过将此代码添加到my_generator.rb来扩展我的生成器中的rails迁移生成器:

require 'rails/generators'
require 'rails/generators/active_record'
require 'rails/generators/actions/create_migration'

class MyGenerator < ActiveRecord::Generators::Base
  source_root File.expand_path('../templates', __FILE__)
  argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"

  def create_migration_file
    set_local_assigns!
    validate_file_name!
    migration_template @migration_template, "db/migrate/#{file_name}.rb"
    # more code here as per requirement.
  end

  # more code below as per requirement..
end

在这里发表这篇文章,希望将来有一天会帮助别人。