15.3. Writing a Generator

The Rails generator system is a simple but powerful way to create a family of files from a set of templates based on user commands. The Rails core defines generators for controllers, models, mailers, integration tests, plugins, scaffolds, and a couple of other things. In addition to supporting more complex plugins, generators can stand on their own to automate repetitive tasks. Examples might include custom scaffolding for controllers and models, standard layout templates, or test suites.

15.3.1. Basic Generator Functionality

Generators are called via the script/generate command. The general format is as follows:

$ruby script/generate generator_name arg1 arg2 --opt1 --opt2

Every generator responds to a set of common option flags, which are described in the following table.

FlagMeaning
-c --svnAdd new files to subversion, if available.
-h --helpShow the help message.
-f --forceOverwrite existing files without asking.
-p --pretendShow the list of files that would be created, but don't actually create any files.
-q --quietNo output.
-s --skipSkip existing files without asking.
-t --backtraceShow a stack trace on error.
-v --verboseVerbose output.

The arguments and options are parsed for you in the parent generator class before your generator is initialized. You have the ability to add new option arguments to your generator.

Generators come in two flavors: basic and named. In a basic generator, the arguments are placed in the instance variable args, and command-line ...

Get Professional Ruby on Rails™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.