← Home
rails

Rails Generate generator

Reference & Command Builder

Published: 2023-05-11
Author: Harrison Broadbent
Type: Reference & Command Builder

Rails Generate Generator

Rails Generate Generator (rails g generator) is the generator for generators 🤯 So many generators...

Generators are built on top of Thor, which provides command parsing and file manipulation APIs; Generators are classes which typically inherit from Rails::Generators::NamedBase.

Generators are composed of methods, which are executed sequentially. You can also define flags with the class_option methods.

A simple generator might look like this —

class ExampleGenerator < Rails::Generators::NamedBase
  desc "An example Rails generator."
  class_option :scope, type: :string, default: "app"
 
  source_root File.expand_path("templates", __dir__)
 
  def copy_initializer_file
    scope = options["scope"]
    copy_file "initializer.rb", "config/initializers/#{scope}/#{file_name}.rb"
  end
 
  def do_something_else
    # runs after #copy_initializer_file
  end
end

You would run the generator like this —

 rails g example helpers --scope dashboard
      create  config/initializers/dashboard/helpers.rb

Where the first argument, helpers, is parsed as the file_name variable, and class_option :scope defines the --scope flag.

If you're looking for a more in-depth guide on building Rails generators, here's a great starting point — Creating custom Rails generators, Garrett Dimon.

Command Builder for rails g generator

rails g generator 

Generator Name

Generator Options

Runtime Options

# Command Options
❯ rails g generator

Usage:
  rails generate generator NAME [options]

Options:
      [--skip-namespace], [--no-skip-namespace]              # Skip namespace (affects only isolated engines)
      [--skip-collision-check], [--no-skip-collision-check]  # Skip collision check
      [--namespace], [--no-namespace]                        # Namespace generator under lib/generators/[name]
                                                             # Default: true
  -t, [--test-framework=NAME]                                # Test framework to be invoked
                                                             # Default:

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

# Command Description
Description:
    Generates a new generator at lib/generators. Pass the generator name as an argument,
    either CamelCased or snake_cased.

Example:
    `bin/rails generate generator Awesome`

    creates a standard awesome generator:
        lib/generators/awesome/
        lib/generators/awesome/awesome_generator.rb
        lib/generators/awesome/USAGE
        lib/generators/awesome/templates/
        test/lib/generators/awesome_generator_test.rb