How do you build a custom Rails 8.1 generator with bin/rails generate generator, and what do NamedBase, source_root and Thor actions give you?
answer
- lib/generators/<name>/ with USAGE, templates
- NamedBase: required name argument plus helpers
- source_root File.expand_path("templates", __dir__)
- public methods run in definition order
- destroy reverses revocable actions only
basics
~20 sbin/rails generate generator reward writes lib/generators/reward/ with a RewardGenerator subclass of Rails::Generators::NamedBase, a USAGE file, a templates folder and a test. NamedBase supplies the name argument and helpers such as file_name; source_root points at templates; each public method runs Thor actions in order.
solid answer
~30 s`bin/rails generate generator reward` writes `lib/generators/reward/reward_generator.rb`, `USAGE`, an empty `templates/` directory and `test/lib/generators/reward_generator_test.rb`. The class inherits `Rails::Generators::NamedBase`, which declares a required `name` argument and derives helpers from it: `file_name`, `class_name`, `plural_name`, `table_name`, `class_path`. `source_root File.expand_path("templates", __dir__)` tells Thor where `template` and `copy_file` read from. Every **public** instance method runs once, in the order defined, and calls actions: Thor's `template`, `copy_file`, `create_file`, `inject_into_file`, `gsub_file`, `directory`, plus Rails' `route`, `initializer`, `gem` and `generate`. `class_option` adds flags read via `options`. `bin/rails destroy reward` replays the methods in revoke mode, which undoes `template` and `route` but skips `gsub_file`. Test it with `Rails::Generators::TestCase`, `run_generator` and `assert_file`.
code
ruby · 18 lines# lib/generators/reward/reward_generator.rb
class RewardGenerator < Rails::Generators::NamedBase
source_root File.expand_path("templates", __dir__)
class_option :points, type: :numeric, default: 2
def create_rule
template "rule.rb.tt", "app/models/rewards/#{file_name}.rb"
end
def create_test
template "rule_test.rb.tt", "test/models/rewards/#{file_name}_test.rb"
end
def register_rule
inject_into_file "config/initializers/rewards.rb",
"Rewards.register Rewards::#{class_name}\n", after: "# rules\n"
end
endgo deeper
Know that bin/rails generate generator scaffolds a generator in lib/generators and that its templates live in a templates folder.
Explain NamedBase's name argument and helpers, source_root, public methods running in order, and the common Thor actions.
Design generators that destroy cleanly, take options, are covered by Rails::Generators::TestCase, and earn their keep by encoding a recurring multi-file change.
Decide when a generator is worth maintaining versus documentation or a gem, and keep generators in step with the conventions they encode.
## Why write a generator A coffee-chain app adds a new **reward rule** every few weeks: a class in `app/models/rewards/`, a test, a translation key and a line registering it. A generator turns that checklist into one command, `bin/rails generate reward double_shot_tuesday`, and makes every new rule start from the same shape. ## Scaffolding the generator `bin/rails generate generator reward` writes: - `lib/generators/reward/reward_generator.rb`; - `lib/generators/reward/USAGE`, the text `--help` prints; - `lib/generators/reward/templates/`, empty; - `test/lib/generators/reward_generator_test.rb`. Rails finds it because `lib` is on the load path and generator lookup tries `generators/reward/reward_generator.rb`, among other names. `--no-namespace` puts the files directly in `lib/generators/` instead. ## NamedBase and source_root The generated class is two lines: ```ruby class RewardGenerator < Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) end ``` **`Rails::Generators::NamedBase`** adds a required first argument, `name`, and helpers derived from it, the same ones Rails' own generators use: | Helper | For `double_shot_tuesday` | |---|---| | `file_name` | `double_shot_tuesday` | | `class_name` | `DoubleShotTuesday` | | `plural_name` | `double_shot_tuesdays` | | `human_name` | `Double shot tuesday` | | `class_path` | `[]` (or `["admin"]` for `admin/double_shot_tuesday`) | Use `Rails::Generators::Base` instead when the generator takes no name, such as an installer. **`source_root`** sets the directory Thor reads templates from. Rails also looks in `lib/templates/reward/` first, so an app can override your templates the way it overrides Rails' own. ## Doing the work Thor runs every **public instance method** once, in the order they are defined. Private methods are helpers. Inside those methods you call actions: 1. **Thor file actions**: `template` (render an ERB `.tt` file with the generator's binding), `copy_file` (copy verbatim), `create_file` (write a string), `directory` (copy a tree), `empty_directory`, `inject_into_file` / `insert_into_file` with `after:` or `before:`, `append_to_file`, `gsub_file`. 2. **Rails actions**: `route`, `initializer`, `lib`, `rakefile`, `gem`, `environment`, `generate` (run another generator) and `rails_command`. 3. **Options**: `class_option :points, type: :numeric, default: 2` adds `--points`, read as `options[:points]`; `argument` declares extra positional arguments. ## Destroy comes almost for free `bin/rails destroy reward double_shot_tuesday` runs the same public methods with `behavior` set to `:revoke`. Actions that know how to reverse themselves do so: `template`, `copy_file` and `create_file` remove their files, `directory` removes the files it copied, `empty_directory` removes its directory, and `inject_into_file` (and therefore `route`) strips the injected text. Others do not: `gsub_file` returns without doing anything on revoke, so Rails' `gem` action, which appends to the Gemfile through `gsub_file`, leaves its line behind, and shell-outs through `run` or `rails_command` are skipped. Design generators so that their edits are injections you can revoke. ## Testing it The generated test uses `Rails::Generators::TestCase`: - `tests RewardGenerator` names the class under test; - `destination Rails.root.join("tmp/generators")` and `setup :prepare_destination` give each test a clean directory; - `run_generator ["double_shot_tuesday"]` runs it; - `assert_file "app/models/rewards/double_shot_tuesday.rb", /class DoubleShotTuesday/` checks the result. ## When a generator is worth it A generator pays off when the same multi-file change recurs and drifts when done by hand. For a one-off, write the files. For changes to Rails' own generated output, override templates instead of writing a new generator. ## Hooks and composition A generator can call others. `generate "migration", "AddTierToRewards tier:string"` runs Rails' migration generator as part of yours, and `hook_for :test_framework` invokes whatever test framework the app has configured, so the same reward generator writes a Minitest test in one app and an RSpec spec in another if a matching sub-generator exists. That is how Rails' own `model` generator stays test-framework agnostic. Keep the generator's own templates in `templates/` as `.tt` files when they need variables, and as plain files with `copy_file` when they do not.
- Why might bin/rails destroy leave changes behind after a custom generator ran?Destroy replays the generator in revoke mode, and only actions that know how to reverse themselves do anything. `template`, `create_file`, `directory` and `inject_into_file` are reversed, but `gsub_file` returns early on revoke and shell commands such as `rails_command` are never undone. Prefer injections over substitutions when you want destroy to work.
- When would you subclass Rails::Generators::Base instead of NamedBase?When the generator has no natural name argument, such as an installer that copies a fixed initializer and adds a gem. `Base` gives the same Thor actions, `source_root` and options without requiring `name`. `NamedBase` is for generators that create something called by name and need `file_name`, `class_name` and friends.
- Private methods in a generator run in definition order too
- source_root lists the files the generator will create
- gsub_file changes are reverted by bin/rails destroy
- NamedBase generators can run without a name argument
- Custom generators must be registered in config.generators to be found