因此,正如@23tux 建议的那样,我继续查看设计 gem 代码库并找到了我需要的解决方案。
在lib/generators/{gem_name} 中,我创建了一个名为{gem_name}_generator 的文件,在其中我能够遵循https://github.com/plataformatec/devise/blob/master/lib/generators/devise/devise_generator.rb 的模式并创建迁移以附加到应用程序中的现有模型。
require 'rails/generators/named_base'
require 'rails/generators/active_record'
module GemName
module Generators
class GemNameGenerator < ActiveRecord::Generators::Base
include Rails::Generators::ResourceHelpers
namespace "gem_name"
desc "Creates GemName Migrations"
source_root File.expand_path("../templates", __FILE__)
def copy_migration
migration_template "migration_existing.rb", "db/migrate/add_gem_name_to_#{plural_name.downcase}"
end
def migration_data
<<RUBY
## Add active column to table
t.datetime :started_trial, :default => Time.now, :after => :id
t.boolean :active, :default => true, :after => :started_trial
t.boolean :allowed_past_trial, :default => false, :after => :active
RUBY
end
end
end
end
class_name 和 plural_name 可以访问,因为我在终端中运行了 $ rails generate gem_name account
因此 class_name = 'account' 和复数名称 = 'accounts'
migration_existing.rb 位于lib/generators/{gem_name}/templates,代码如下:
class AddGemNameTo<%= plural_name.camelize %> < ActiveRecord::Migration
def self.up
change_table(:<%= plural_name %>) do |t|
<%= migration_data %>
end
end
def self.down
# By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration.
raise ActiveRecord::IrreversibleMigration
end
end