【问题标题】:Add Migrations to a Rails Engine's Install Generator将迁移添加到 Rails 引擎的安装生成器
【发布时间】:2017-01-16 20:43:09
【问题描述】:

在我的 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

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

【问题讨论】:

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


    【解决方案1】:

    有趣的问题!我希望我能回答一个。假设您有一个名为“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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多