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?
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With