将迁移添加到Rails引擎的安装生成器

时间:2016-09-08 19:43:12

标签: ruby-on-rails rails-migrations rails-engines rails-generators

在我的rails 5引擎中,我想用我在的自定义安装生成器中包含引擎迁移的安装:

myengine / LIB /发电机/ myengine / install_generator.rb

此生成器目前看起来像这样:

module Myengine
  module Generators

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

      desc "Creates a Myengine initializer and copys template files to your application."

      def copy_initializer
        template "myengine.rb", "config/initializers/myengine.rb"
      end

    end
  end
end

当我将引擎添加到rails应用程序时,而不是必须调用:

rails g myengine:install

然后

rails myengine:install:migrations

如何将这些迁移的创建添加到自定义生成器?

1 个答案:

答案 0 :(得分:3)

有趣的问题!还有一个我希望我能回答的问题。让我们假设你有一个名为&#34; Buttafly&#34;以及生活在:

的发电机
#lib/generators/buttafly/install/install_generator.rb

在您的生成器的顶部,需要&#39; date&#39;像这样的图书馆:

require 'date'

然后在生成器的主体中添加一个方法定义,如:

  def copy_migrations

    # get an array of the migrations in your engine's db/migrate/ 
    # folder:

    migrations = Dir[Buttafly::Engine.root.join("db/migrate/*.rb")]
    migrations.each_with_index do |migration, i|

    # The migrations will be created with the same timestamp if you 
    # create them all at once. So if you have more than one migration 
    # in your engine, add one second to the second migration's file
    # timestamp and a third second to the third migration's timestamp 
    # and so on:

    seconds = (DateTime.now.strftime("%S").to_i + i).to_s
    seconds = seconds.to_s.length == 2 ? seconds : "0#{seconds}"
    timestamp = (DateTime.now.strftime "%Y%m%d%H%M") + seconds

    # get the filename from the engine migration minus the timestamp:
    name = migration.split("/").split("_").last

    # See if a the name of your engine migration is already in your
    # host app's db/migrate folder:

    if Rails.root.join("db/migrate/*#{name}").exist?

      # do nothing:
      puts "Migration #{name} has already been copied to your app"
    else

      # copy your engine migration over to the host app with a new 
      # timestamp:
      copy_file m, "db/migrate/#{timestamp}_buttafly_#{name}"
    end
  end
end