skip to content

What is a Rails application template, and how does bin/rails app:template apply one to an existing Rails 8.1 app?

level: middleimportance: nice to knowfreq 16%

answer

  1. plain Ruby run with the generator API
  2. LOCATION=path or URL
  3. gem, generate, route, rails_command
  4. bundle, then after_bundle blocks
  5. remote template means running remote code

basics

~10 s

An application template is a Ruby script run with Rails' generator actions (gem, generate, route, initializer, rails_command). bin/rails app:template LOCATION=path-or-URL applies it to an existing app, then runs bundle install and the after_bundle blocks.

solid answer

~40 s

A template is a plain Ruby file, usually `template.rb`, evaluated inside Rails' app generator, so it can call every Thor and Rails generator action: `gem`, `gem_group`, `generate`, `route`, `initializer`, `environment`, `rails_command`, `inject_into_file`, plus `yes?` and `ask` for prompts. `bin/rails app:template LOCATION=~/templates/coffee.rb` (or an `https://` URL) boots the app, applies the template to `Rails.root`, runs `bundle install`, then runs the `after_bundle` blocks, which is where generators from newly added gems and `git` commits belong. `LOCATION` is required; the task raises without it. The same file can be passed to `rails new -m` when creating an app. Because a template is arbitrary Ruby, applying one from a URL runs someone else's code on your machine, so read it first.

code

ruby · 12 lines
ruby
# coffee_template.rb
gem "pagy"
initializer "store_hours.rb", <<~RUBY
  Rails.application.config.x.store_opens_at = "07:00"
RUBY
route "get 'up/stores', to: 'stores#health'"

after_bundle do
  generate :model, "Store name:string city:string"
  rails_command "db:migrate"
  git add: ".", commit: %(-m "Apply coffee template")
end

go deeper

for a junior

Know that a template is a Ruby script that automates app setup, applied with bin/rails app:template LOCATION=... .

for a middle

Explain the template API (gem, generate, route, rails_command), the bundle then after_bundle order, and how templates differ from generators.

for a senior

Write templates that are reviewable and safe to apply to existing apps, and refuse to run unreviewed remote templates.

for a principal

Use templates to standardize new services across teams, and decide what belongs in a shared template versus a gem or engine that can be upgraded.

## Templates versus generators Both use the same action API, but they solve different problems: | | Generator | Application template | |---|---|---| | Shape | a class in `lib/generators` | a Ruby script, often `template.rb` | | Run with | `bin/rails generate name` | `bin/rails app:template LOCATION=...` or `rails new -m` | | Repeated? | many times, once per thing generated | usually once per app | | Typical job | create a model, a reward rule, a component | set up an app: gems, config, CI, initial generators | A coffee-chain company that starts a new internal app every quarter might keep `coffee_template.rb` that adds its auth gem, its logging initializer, a health-check route and its CI file. ## What a template can call The script is evaluated inside an instance of Rails' app generator, so it has the whole generator API: - **Gemfile**: `gem "pagy"`, `gem_group :development, :test do ... end`, `add_source`; - **files**: `initializer "logging.rb", "..."`, `lib`, `rakefile`, `file`, `inject_into_file`, `gsub_file`, `copy_file`; - **configuration**: `environment "config.time_zone = 'Europe/Berlin'"`, optionally with `env: "production"`; - **code generation**: `generate :model, "Store name:string"`, `route "root to: 'stores#index'"`; - **commands**: `rails_command "db:migrate"`, `run "..."`, `git add: "."`; - **interaction**: `yes?("Add Pagy?")`, `ask("Admin email?")`. ## How app:template runs `bin/rails app:template` is a Rake task defined in Rails' framework tasks: 1. It depends on `:environment`, so the app boots first. 2. It reads `ENV["LOCATION"]` and raises `No LOCATION value given` when it is blank. 3. It calls the app generator's `apply_rails_template` with that location and `Rails.root` as the destination, so every action targets the existing app. 4. It runs `bundle install`, then the blocks registered with **`after_bundle`**. That order matters: a gem added with `gem` is not installed until step 4, so its generators (`generate "pagy:install"`-style calls) belong inside `after_bundle`, not at the top level. `LOCATION` can be a local path or an `http(s)` URL, and the same file works with `rails new myapp -m coffee_template.rb` at creation time. ## Safety and repeatability - A template is **arbitrary Ruby**. The guide warns that a remote template can do anything your user can do, from deleting files to uploading private keys. Download it, read it, then run the local copy. - Templates are not automatically **idempotent**. Running one twice may add a gem twice or inject a line twice. Guard with checks such as `File.read("Gemfile").include?("pagy")`, or design it to run once. - Commit before applying, so `git diff` shows exactly what the template changed. ## When to use one - Standardizing **new apps** across a team or company. - Applying a **one-time setup** to several existing apps, such as adding the same CI file and initializer. - Not for recurring per-feature code: that is a generator's job. ## Templates and generators together A template often ends by calling generators: `generate :model, ...` for the first domain models, or a gem's installer inside `after_bundle`. The reverse also happens: a team's custom generator may be added to every new app by a template that copies `lib/generators/...` into place. The template sets the app up once; the generators it installs keep producing consistent code afterwards. ## Keeping templates maintainable - Store them in a repository and version them with the Rails release they target. - Re-run them against a fresh `rails new` after each Rails upgrade, because generated files they edit may have changed. - Keep each template short and focused; several small templates applied in sequence are easier to review than one large script.

  • Why must generate calls for a gem added by the template sit inside after_bundle?
    `gem` only edits the Gemfile. `app:template` runs `bundle install` after the whole script has been applied, and only then runs the `after_bundle` blocks. A generator provided by the new gem does not exist until the gem is installed, so calling it at the top level fails, while inside `after_bundle` it runs after installation.
  • What should you check before applying a template from a URL?
    Read the script. It is ordinary Ruby running with your permissions, so it can run shell commands, edit any file or send data out. Download it, review it, commit your app first, and apply the local copy, so you know exactly what ran and can diff the result.

  • Application templates are YAML files describing the app
  • bin/rails app:template works without LOCATION and picks a default
  • Generators from a gem added by gem can run before bundling
  • Applying a remote template is sandboxed by Rails
  • app:template can only be used when creating a new app