Posts Rails 3 generators in gem
Post
Cancel

Rails 3 generators in gem


This is the folders structure in a gem.

lib
  - generators
    - gemname
      install_generator.rb
      - templates
        (template files)
        

Install Generator

require 'rails/generators'

module ModuleName
  module Generators
    class InstallGenerator < Rails::Generators::NamedBase
      include Rails::Generators::Migration
      
      source_root File.expand_path("../templates", __FILE__)
      
      generators...
      
      def self.next_migration_number(path)
          @migration_number = current_migration_number(path) + 1
          ActiveRecord::Migration.next_migration_number(@migration_number)
      end
  
    end
   
  end
end

Generators

def generators
           
    generate("controller" , "nameOfController")
    
    copy_file "fileWantYouCopy.rb"   , "app/models/destiniAndNameToCopiedFile.rb"
    
    migration_template("modelOfMigrate.rb"  , "db/migrate/modelOfMigrateDestini.rb")
end

Migration template

You need add this include to use migration_template

include Rails::Generators::Migration

You need to implement next_migration_number

def self.next_migration_number(path)
      @migration_number = current_migration_number(path) + 1
      ActiveRecord::Migration.next_migration_number(@migration_number)
end

Updated May 12, 2020 2020-05-13T06:35:06+08:00
This post is licensed under CC BY 4.0