Conquer the Rails Configuration Process Using Shell Script
Tell me if this sounds familiar: Because Rails doesn’t include many of the configurations that you prefer, you spend way too much time configuring before you can actually get to the code. Not only is this process mind-bendingly repetitive but it is also brittle — in your annoyed state of mind, you might forget something.
My configuration process is as follows:
- Tell Rails to not use minitests or sqlite
- Populate the Gemfile with my preferred gems
- Bundle install
- Install RSpec
- Update the ruby gemset and ruby version files
- Implement a system to protect the secret token
- Update the database.yml file and create an example database.yml file
- Gitignore the sensitive documents such as secret token and database.yml
- Initialize git
Whenever I start a new project, I find that I rarely ever remember to do all of these things. So I set out to automate it for me.
At first, I tried to use Rails’ built in generator. I ultimately settled on writing shell scripts for the command line for two reasons: the Rails generator has trouble performing meta-tasks such as adding or removing the application’s name to a file and shell scripts allow you to break out each step of the process piece by piece so that if needed, you could call one of the sub-routines.
In this essay, I’m going to go through the script that I wrote and explain what it does. You can find the full file here:
Initialization
The core of the script is the “rails_new” command. Just like the familiar “rails new,” you would pass in the name of the application you want to build. For example:
rails_new sample_appNow let’s go to my .bashrc file to look at this function in pieces.
#~/.bashrc
function rails_new() {
rails new $1 -T -B -d=postgresql &&
cd $1 &&
...
}The first line calls the traditional rails new and passes it the first argument that was given to rails_new. In a shell script function, $1 means the first argument that was passed in. In our example, that would be the string “sample_app.” One of the advantages of the shell script over the Rails generator is that we can pass this $1 all around function.
The -T flag tells Rails not to use the default minitests suite, the -B flag tells Rails not to bundle install since we have our own gems to add before we want to bundle, and the -d=postgresql flag tells it to use postgreSQL instead of sqlite.
Finally, we cd into the app itself in order to start doing configuration tasks.
Populating the Gemfile
function rails_new() {
...
echo “populating gemfiles” &&
populate_gemfile &&
...
}Next, we will populate the Gemfile. the rails_new function here calls a separate function populate_gemfile, which is given by:
function populate_gemfile() {
echo “gem ‘haml’” >> Gemfile &&
echo “gem ‘simple_form’” >> Gemfile &&
echo “” >> Gemfile &&
echo “group :test do” >> Gemfile &&
echo “ gem ‘factory_girl_rails’” >> Gemfile &&
echo “end” >> Gemfile &&
echo “” >> Gemfile &&
echo “group :test, :development do” >> Gemfile &&
echo “ gem ‘rspec-rails’” >> Gemfile &&
echo “ gem ‘pry-rails’” >> Gemfile &&
echo “ gem ‘launchy’” >> Gemfile &&
echo “ gem ‘valid_attribute’” >> Gemfile &&
echo “ gem ‘shoulda-matchers’” >> Gemfile &&
echo “ gem ‘quiet_assets’” >> Gemfile &&
echo “ gem ‘capybara’” >> Gemfile &&
echo “end” >> Gemfile &&
echo “” >> Gemfile &&
echo “group :production do” >> Gemfile &&
echo “ gem ‘rails_12factor’” >> Gemfile &&
echo “end” >> Gemfile
}The shovel operator (>>) here tells the shell to write the output of the previous command onto a new line in the designated file. The output of echo gem ‘haml’ is “gem ‘haml’” which then gets added to the Gemfile. By being creative with the spacing, you can create that nesting effect when you specify environment groups. An added bonus is that you can see the nesting occur in the script itself.
Of course, these gems are my preferred set. I highly urge you to alter these to your tastes.
Populate .ruby-gemset and .ruby-version
These two files tell the app which gemset to use and which ruby version to use. It generally works out fine if you don’t have them but they can really bite you hard if some conflicts occur, so I generally include them.
In the rails_new function, these two actions are aliased to two sub-functions.
function rails_new() {
...
echo “populating ruby gemset file” &&
populate_ruby_gemset_file $1 &&
echo “populating ruby version file” &&
populate_ruby_version_file &&
cd .. && cd $1 &&
...
}The two sub-functions look like this:
function populate_ruby_gemset_file() {
echo $1 >> .ruby-gemset
}function populate_ruby_version_file() {
ruby -v | cut -d ‘ ‘ -f 2 | cut -d p -f 1 >> .ruby-version
}
populate_ruby_gemset_file is pretty easy to explain: by default, the ruby gemset of the application is given the same name of the application. So all we need to do is take the name of the application and shovel it in.
populate_ruby_version_file is a bit more complicated but the idea is the same. ruby -v calls the current version of ruby, which comes out in this format:
ruby 2.0.0p353 (2013-11-22 revision 43784) [x86_64-darwin13.0.0]That’s no good, as all you want is the version number. The cut command in shell script is like the split method in ruby. -d specifies the delimiter and -f returns the element at the specified index. So I take the output of ruby -v and split it by space and return the second element, which is “2.0.0p353.” Next, I split it again by p and return the first element, which returns “2.0.0.” I take that and I shovel it into the .ruby-version file.
Get Mo Zhu’s stories in your inbox
Join Medium for free to get updates from this writer.
Finally, I must cd out of the file and then back in, which makes the computer reload these two files so that they are part of the current configuration.
Secret Token
Rails uses a secret token as a verification tool for session management. This means that you shouldn’t put your secret token online in a public repository. The problem is that if you simply gitignore your config/secret_token.rb file, every time you do something with your app, you’ll need to generate a new secret token. What a pain.
There are many ways to deal with this issue. I use Michael Hartl’s solution, which is found in his Rails book.
function rails_new() {
...
echo “completing secret token process” &&
secret_token_process $1 &&
...
}The rails_new command calls the secret_token_process command, which is passed the first argument of the rails_new command. In our example, this is “sample_app.”
secret_token_process runs as follows:
function secret_token_process() {
echo “.secret” >> .gitignore &&
cd config/initializers &&
rm -f secret_token.rb &&
touch secret_token.rb &&
echo “require ‘securerandom’” >> secret_token.rb &&
echo “def secure_token” >> secret_token.rb &&
echo “ token_file = Rails.root.join(‘.secret’)” >> secret_token.rb &&
echo “ if File.exist?(token_file)” >> secret_token.rb &&
echo “ File.read(token_file).chomp” >> secret_token.rb &&
echo “ else” >> secret_token.rb &&
echo “ token = SecureRandom.hex(64)” >> secret_token.rb &&
echo “ File.write(token_file, token)” >> secret_token.rb &&
echo “ token” >> secret_token.rb &&
echo “ end” >> secret_token.rb &&
echo “end” >> secret_token.rb &&
convert_filename_to_camelcase $1 >> secret_token.rb &&
echo “::Application.config.secret_key_base = secure_token” >> secret_token.rb &&
cd ../..
}we will put the full secret token into the .secret file in the root directory of the application. This secret token should not be saved as part of git, so it should first be placed in the .gitignore file.
Next, we cd into the config/initializers directory since that’s where the secret_token.rb file resides. We delete it and create a new one. Then we populate the new one with Hartl’s approach to the secret token. Specifically, the token is read from the .secret file in the root directory. If that file does not exist, then it creates one and populates it with a random string.
The secret_token.rb file, per Hartl’s method, should end with the line
SampleApp::Application.config.secret_key_base = secure_tokenHowever, as you’ll note, $1 is “sample_app,” not the camel-cased “SampleApp.” I convert $1 to camel-case in the convert_filename_to_camelcase function.
function convert_filename_to_camelcase() {
echo -n $1 |
ruby -e “print STDIN.gets.split(‘_’).map(&:capitalize).join”
}echo -n here echoes without a newline character at the end of the echo. We do this because we don’t want SampleApp and ::Application to be on separate lines.
The ruby -e command allows us to write ruby code directly in the terminal. So we take $1 and pass it into the ruby code via STDIN.gets. We split “sample_app” by the “_” and then capitalize each item then join them together. This returns “SampleApp.”
Returning to the secret_token_process function, that output gets shoveled into the secret_token.rb file and then the remainder of the line is attached.
You can read more about Hartl’s secret token process here.
Finally, we cd back to the application root directory to continue the script.
Administrivia
The next section contains some simple matters that will be quick to go through:
function rails_new() {
...
bundle install &&
echo “installing rspec” &&
rails generate rspec:install &&
echo “require ‘capybara/rspec’” >> spec/spec_helper.rb &&
echo “creating folders for specs and factories” &&
create_folders &&
...
}This just simply calls bundle install, installs RSpec, adds Capybara to the spec_helper.rb file and then creates folders for features and factories since they will almost certainly be used.
Database.yml
Finally, rails_new will manage all that database.yml business.
function rails_new() {
...
echo “copying and fixing database.yml file”
mv config/database.yml config/database.example.yml &&
fix_database_example_yml_file $1 &&·
cpdatabase &&
echo “config/database.yml” >> .gitignore &&
...
}First, it will rename database.yml to database.example.yml.
If I were doing this manually, I would next go to the database.yml.example file and delete the username three times from the file for each environment. I’ve eliminated that step with the fix_database_example_yml_file method.
By default, the username found in the database.yml file is the name of the app. So we pass the function $1.
function fix_database_example_yml_file() {
sed -i ‘’ “s/\(username:\) $1/\1/” config/database.example.yml
}In the command line, sed is a string replacement tool. There is a lot going on in here, so I will just point you to the most comprehensive sed guide on the internets. Ultimately, the usernames are deleted from the database.example.yml files.
Next, we run cpdatabase, which will copy the revised database.example.yml file into a database.yml file.
alias cpdatabase="cp config/database.example.yml config/database.yml"Initialize git
Finally,
function rails_new() {
...
git_init_add_commit
}rails_new calls the git_init_add_commit function, which does what you think it does.
function git_init_add_commit() {
git init &&
git add . &&
git commit -m “initial commit”
}It initializes git, stages all the changes that were made, and then commits them. The commit message is set to “initial commit.”
And voila! That’s how you automate your initialization sequence for a new Rails project.






