Setup your rails application with one command

bundle bundle exec rails db:create bundle exec rails s We can create a script and run it to setup our application since Rails 4.2 a bin/setup file is generated by default. Here is the example of setup script.

#!/usr/bin/env ruby
require 'pathname'
require 'fileutils'
include FileUtils
# path to your application root.
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
def system!(*args)
  system(*args) || abort("\n== Command #{args} failed ==")
end
chdir APP_ROOT do
  # This script is a starting point to setup your application.
  # Add necessary setup steps to this file.
  puts '== Installing dependencies =='
  system! 'gem install bundler --conservative'
  system('bundle check') || system!('bundle install')
  # puts "\n== Copying sample files =="
  # unless File.exist?('config/database.yml')
  #   cp 'config/database.yml.sample', 'config/database.yml'
  # end
  puts "\n== Preparing database =="
  system! 'bin/rails db:setup'
  puts "\n== Removing old logs and tempfiles =="
  system! 'bin/rails log:clear tmp:clear'
  puts "\n== Restarting application server =="
  system! 'bin/rails restart'
end
Setup script sets your rails application for development environment instantly.  This is helpful when a new developer trying to set up your application or when setting up an application on a new machine. We should keep the setup script updated. Let’s understand the setup script step by step and modify according to our requirements. First setup basic required library and path of our application in APP_ROOT
#!/usr/bin/env ruby
require 'pathname'
require 'fileutils'
include FileUtils
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
Now system! method here execute the commands passed to it and shows the backtrace of error in case of command fails.
def system!(*args)
  system(*args) || abort("\n== Command #{args} failed ==")
end
system will execute the given rails command and abort will stop script execution and will show us the backtrace of failed command, we can modify it if we don’t want to stop the execution of the script and get some custom error messages.
def system!(*args)
  system(*args) || puts "#{args} -> FAILED TO EXCECUTE"
end
In the below snippet of the script, we are going to our application root and performing operations.
chdir APP_ROOT do
  puts '== Installing dependencies =='
  system! 'gem install bundler --conservative'
  system('bundle check') || system!('bundle install')
  puts "\n== Preparing database =="
  system! 'bin/rails db:setup'
  puts "\n== Removing old logs and tempfiles =="
  system! 'bin/rails log:clear tmp:clear'
  puts "\n== Restarting application server =="
  system! 'bin/rails restart'
end
To create config file if not already exist, modify your script as
   puts "== Copying sample files =="
   unless File.exist?('config/database.yml')
     cp 'config/database.yml.sample', 'config/database.yml'
   end
]]>