Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how to extend a generator?

I'm trying to extend the model generator in Rails ( rails g model ). Basically my generator should do the same thing as the model one, but copy 2 additional files. Simple as that.

I reviewed Railscast #218 ( http://railscasts.com/episodes/218-making-generators-in-rails-3 ) which was very informative but i couldn't find any info about extending generators.

Checking the source code of rails, it looks like the model generator is in lib/rails/generators/rails/model/model_generator.rb defined as Rails::Generators::ModelGenerator.

I tried to make my generator extend this class but it results in:

Error: uninitialized constant Rails::Generators::ModelGenerator.

And my attempts to require this file were not successful.

So I decided to stop and ask here. What is the proper way of extending a generator?

like image 464
Fernando Avatar asked Nov 04 '22 07:11

Fernando


2 Answers

Take a look at hooks and invoke.

class MyGenerator < Rails::Generators::Base
  def create_my_file
    # Do your generators stuff
    create_file "config/initializers/my.rb", "# Add content here"
    # Create model
    invoke("model", ["model_name", "arg1", "arg2"])
  end
end

Hope this help.

like image 154
nyzm Avatar answered Nov 15 '22 05:11

nyzm


  1. Generate your custom generator:

    rails generate generator my_model
    
  2. Open lib/generators/my_model/my_model_generator.rb and change it to:

    require 'rails/generators/active_record/model/model_generator'
    
    class MyModelGenerator < ActiveRecord::Generators::ModelGenerator
      source_root File.expand_path('../templates', __FILE__)
    end
    

This works for rails engines. Don't forget to add required templates.

like image 32
Roman Trofimov Avatar answered Nov 15 '22 06:11

Roman Trofimov