2

在我的 rails 5 引擎中,我想将引擎迁移的安装与我在以下位置的自定义安装生成器一起安装:

myengine/lib/generators/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

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

4

1 回答 1

4

有趣的问题!我希望我能回答一个。假设您有一个名为“Buttafly”的引擎和一个位于以下位置的生成器:

#lib/generators/buttafly/install/install_generator.rb

在生成器的顶部,需要像这样的“日期”库:

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
于 2018-01-31T06:39:03.237 回答