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 possib
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.
The correct position for your customized controller file is lib/templates/rails/scaffold_controller/controller.rb
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
If anyone is wondering why this isn't working in a default Rails 4 install, it's because jbuilder is inserting itself into the template path before the override location. I don't need jbuilder so I removed it, but I also reported an issue in Github. Hopefully it'll be fixed soon.
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