LoginSignup
2
1

More than 5 years have passed since last update.

カスタムでmodelを生成するジェネレータを作る

Last updated at Posted at 2017-04-26

Rails5でmodelを生成するジェネレータを作る方法を調べました。まず、ジェネレータの雛形を生成します。

$ bin/rails g generator xxx

それで、生成されたファイルにして、あとはtemplateディレクトリにmode.rbunit_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_numbermigration_versionmigration_templateを呼ぶのに必要なメソッドです。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1