How to override Rails' default migration generator template
Asked Answered
M

1

5

I need to override these migration templates:

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

inside my rails application so that they pick up the template from rails application instead of the gem itself. I've tried all possible combinations so far but no luck.

What I've tried:

- 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

Can anyone point me into the right direction?

Merkle answered 7/8, 2014 at 15:34 Comment(0)
M
8

I figured out a workaround for my case:

I create a Rails generator with this command(inside my Rails app directory) -

rails g generator my_migrator

It creates:

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

Then I added this code to extend the rails migration generator in my generator by adding this code to my_generator.rb:

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

Posted this here in a hope that it'll help someone some day in future.

Merkle answered 19/8, 2014 at 8:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.