Rails5でmodelを生成するジェネレータを作る方法を調べました。まず、ジェネレータの雛形を生成します。
$ bin/rails g generator xxx
それで、生成されたファイルにして、あとはtemplate
ディレクトリにmode.rb
とunit_test.rb
を書けば、次のようにxxx_generator.rb
を書けば最低限bin/rails g model xxx
と同等の処理がbin/rails g xxx table_name
で生成されます(標準ではあとフィクスチャーのymlファイルが生成されるのですが)。
class XxxGenerator < Rails::Generators::NamedBase
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
def copy_migration
migration_template "migration.rb", "db/migrate/create_#{table_name}.rb", migration_version: migration_version
end
def generate_model
template "model.rb", "app/models/#{table_name.singularize}.rb"
template "unit_test.rb", "test/models/#{table_name.singularize}_test.rb"
run("bin/rails db:environment:set RAILS_ENV=test")
run("bin/rails db:migrate RAILS_ENV=test")
end
def self.next_migration_number(dir)
Time.now.utc.strftime("%Y%m%d%H%M%S")
end
def migration_version
"[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]"
end
private
def model_name
table_name.singularize.camelize
end
end
next_migration_number
とmigration_version
はmigration_template
を呼ぶのに必要なメソッドです。