Rails Application Templates

Ever wondered that you run usual rails new my_awesome_app and you get a really fully bootstraped, authentication added, administration added and lot more for you to just start focusing on business logic instead? Or the other scenario is what if you want all your team to use same versions of Gems i.e. Rails, PostgreSQL. This write up is just about that. Cheers. Words from official guides…

Application templates are simple Ruby files containing DSL for adding gems/initializers etc. to your freshly created Rails project or an existing Rails project.

As this is created on top of Thor so all Thor commands are available plus these actions

  • gem — add gem to Gemfile
  • gem_group — adds group in file
  • environment — adds code inside appliaction.rb or in specific environment file.
  • initializer
  • git — adds git repo
  • generate — runs traditional rails g
  • after_bundle hook — Yes, as name is self explanatory
  • Check all options Rails Official Guides

According to me this is lot to get a quick great start. What I would like to add into my starting application is…

  • pg
  • activeadmin
  • devise
  • bootstrap
  • set root to some controller index 🙂

Lets quickly look at deadsimple example.

def add_gems
 gem 'pg'
 gem 'activeadmin'
 gem 'cancancan'
 gem 'bootstrap'
def add_announcements
  generate "model Announcement published_at:datetime  announcement_type name description:text"
  route "resources :announcements, only: [:index]"
def add_models_to_admin
  files = (Dir.entries Dir.pwd << "/app/models/").reject {|f|  File.directory?(f) }
  files.delete "concerns"
  files.delete "application_record.rb"
  files.each do |mod|
    class_name = mod.split('.').first.classify
    generate "active_admin:resource #{class_name}"
def add_activeadmin
  generate "active_admin:install"
  inject_into_file("config/initializers/active_admin.rb", "config.site_title = 'Rails.application.class.parent_name'", after: "ActiveAdmin.setup do |config|")
def add_seed_data
  insert_into_file("db/seeds.rb", "User.create!(email: 'user@example.com', password: 'password', password_confirmation: 'password') if Rails.env.development?")
def stop_spring
  run "spring stop"

In above we just declared some functions to be called later you can call in any sequence but in this particular case we will do something like this

after_bundle do
 rails_command "db:drop" 
 rails_command "db:create"
 rails_command "db:migrate"
 rails_command "db:seed"
 #This will initialize and commit all new changes in git 
 git :init
 git add: "."
 git commit: %Q{ -m 'First commit' }

Save all the code in my_awesome_template.rb and now you can run same rails new command like this

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s