Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new migrations from Rails engine gem to app via generator

I'm building a Rails engine in a ruby gem. It includes some migrations right now that are called when you run:

rails g myengine:install

The code in the generator is as follows:

module MyEngine
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      include Rails::Generators::Migration

      source_root File.expand_path('../templates', __FILE__)

      # ...

      def copy_migrations
        migration_template "migrations/migration1.rb", "db/migrate/migration1.rb"
        migration_template "migrations/migration2.rb", "db/migrate/migration2.rb"
      end

      # ...
    end
  end
end

However, if I run rails g myengine:install again, it fails with this error:

Another migration is already named migration1: /Users/jh/Code/Web/demoapp/db/migrate/20130327222221_migration1.rb

I want it to just silently ignore the fact that there's already a migration and continue on to the next migration. What would be the best way to do this?

EDIT:

Per Dmitry's answer, this was my solution:

  def copy_migrations
    copy_migration "migration1"
    copy_migration "migration2"
  end

protected

  def copy_migration(filename)
    if self.class.migration_exists?("db/migrate", "#{filename}")
      say_status("skipped", "Migration #{filename}.rb already exists")
    else
      migration_template "migrations/#{filename}.rb", "db/migrate/#{filename}.rb"
    end
  end
like image 863
Jamon Holmgren Avatar asked Mar 27 '13 22:03

Jamon Holmgren


1 Answers

Using migration_template in Rails as example, you could perhaps check for destination = self.class.migration_exists?(migration_dir, @migration_file_name) and if migration already exists, skip over making migration_template call.

like image 128
Dmitry Frenkel Avatar answered Nov 20 '22 08:11

Dmitry Frenkel