Search code examples
ruby-on-railstemplatescontrollergeneratorscaffolding

Rails custom scaffolds


I use two templates to create my controllers in my Rails apps. I've been able to customize my scaffold to handle one of my templates using this tutorial. I was wondering if there is a way to create two scaffolds. I'd like to be able to call rails generate scaffold1 This and rails generate scaffold2 That and produce my custom controllers.


Solution

  • Yes, this can be done.

    It's documented here, and I'll go over the points:

    • 'scaffold' is just a 'generator'
    • generators are built on thor
    • generators themselves have a generator
    • You can create your own generators fairly easily by adding files in lib/generators/

    Example from the page:

    The first step is to create a file at lib/generators/initializer_generator.rb with the following content:

    class InitializerGenerator < Rails::Generators::Base
      def create_initializer_file
        create_file "config/initializers/initializer.rb", "# Add initialization content here"
      end
    end
    

    It's then invoke the generator with rails generate initializer, just like you would run rails generate scaffold (except the initializer above doesn't accept additional values)