Rails quick tips #5: Create apps from templates

- ruby rails

If you often create new Rails apps, application templates can be a real timesaver.

They have a very simple API, which allows developers to make changes to the Gemfile, execute Rails or Git commands, manage files and more.

Here’s a simple template I use to generate a new Rails app with Devise already set up:

gem 'devise'

after_bundle do
  rails_command 'generate devise:install'
  rails_command 'generate devise User'

The first line adds Devise to the Gemfile and the after_bundle hook runs two generators provided by the gem after the app is done bundling.

To generate an app from this template we need to add the -m option to rails new:

$ rails new my_app -m ~/src/rails-templates/devise.rb
# lots of output

After the app is done, let’s verify that Devise was installed and the generators ran correctly:

$ rg devise Gemfile*
56:gem 'devise'

78:    devise (4.7.1)
219:  devise

$ head -n5 config/initializers/devise.rb
# frozen_string_literal: true

# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|

$ cat app/models/user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

Note that we can also execute a template in the context of an already generated app:

$ rails app:template LOCATION=~/src/rails-templates/devise.rb

Making it interactive

The template API allows for some interactivity via the ask and yes?/no? methods:

if yes?("Add devise?")
  gem 'devise'

  after_bundle do
    rails_command 'generate devise:install'
    rails_command "generate devise #{model}"

This will interrupt app generation to ask for user input:

       apply  /Users/michi/template.rb
  Add devise? y
     gemfile    devise
         run  bundle install


For anyone creating lots of Rails apps, custom templates can be a real time-saver. I favor an approach of having many smaller for dedicated tasks and adding them an already created project as needed.

Comments powered by Talkyard.