Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default scaffold generator in rails 3

I've created a generator for a controller in rails 3. Now I want to use this generator as the default generator when using the scaffolding generator.

Is that possible?

like image 927
Linus Oleander Avatar asked Jan 07 '11 22:01

Linus Oleander


4 Answers

The correct position for your customized controller file is lib/templates/rails/scaffold_controller/controller.rb

like image 78
Iwan B. Avatar answered Nov 06 '22 04:11

Iwan B.


If you simply want to use your own controller template, you can just put it in lib/templates/rails/scaffold_controller/controller.rb

If you want to replace the scaffold_controller_generator code itself, for example, so that the controller scaffold generates additional class files. you can create lib/generators/rails/my_scaffold_controller/my_scaffold_controller_generator.rb with templates under lib/generators/rails/my_scaffold_controller/templates.

Remember to point rails at your new scaffold_controller in config/application.rb:

config.generators do |g|
  g.scaffold_controller = "my_scaffold_controller"
end

For my_scaffold_controller_generator.rb you could copy from the railties gem under railties-3.x.x/lib/rails/generators/rails/scaffold_controller if you want to modify default behaviour, or inherit from it if you just want to add functionality:

require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'

module Rails
  module Generators
    class MyScaffoldControllerGenerator < ScaffoldControllerGenerator
      source_root File.expand_path("../templates", __FILE__)

      def new_funtionality
      end

    end
  end
end
like image 33
jackpipe Avatar answered Nov 06 '22 04:11

jackpipe


You can override the templates that Rails uses for its generators. In this instance, just place the file at lib/templates/scaffold_controller/controller.rb and modify it how you wish. The next time you run rails g scaffold [modelName] it will pick up this new controller template and use it.

This is covered in Section 6 of the Creating and Customizing Rails Generators official guide.

like image 36
Ryan Bigg Avatar answered Nov 06 '22 04:11

Ryan Bigg


This seems to have changed slightly with Rails 4. You can see which template the generator will look for in the invoke line when the scaffold is generated, and your template folder name should match this:

rails generate scaffold blub 
...
invoke  responders_controller

If you're using rails g scaffold_controller blubs the location of the template should be:

lib/templates/rails/scaffold_controller/controller.rb

If you're using rails g scaffold blub the location of the template should be:

lib/templates/rails/responders_controller/controller.rb
like image 30
Kenny Grant Avatar answered Nov 06 '22 03:11

Kenny Grant