Automating Application Setup with the bin/setup Command
Learn about the process of automating the setup of Rails applications using the bin/setup command.
We'll cover the following
The bin/setup
script in Rails
Rails provides a bin/setup
script that is decent but imperfect. We want our bin/setup
to be a bit more user-friendly, but we also want it to be idempotent, meaning it has the exact same effect every time it’s run. Right now, that means it must blow away and recreate the database. Many developers infrequently reset their local database. The problem with this is that the local database builds up cruft, which can inadvertently create dependencies with tests or local workflows, and this can lead to complicated and fragile setups just to get the app working locally.
Worse, we might use a copy of the production database to seed local development databases. This is a particularly unsustainable solution because it puts potentially personal user information on our computer and becomes slower and slower to copy over time as the database size increases. If, instead, we create a culture on our team where the local development database is blown away regularly, it creates a forcing function to:
- Not depend on particular data in our database to do work.
- Motivate us to script any such data we need in the
db/seeds.rb
file so everyone can have the same setup.
We want to create a situation where developers new to the app can pull it down from version control, set up Postgres, run bin/setup
, and be good to go. We also want existing developers to get into the habit of doing this frequently. As the app gets more and more complex to set up, this script can automate all of that, and we don’t need to worry about documentation going out of date.
Let’s replace the Rails-provided bin/setup
with one of our own. Remember, this script runs before any gems are installed, so we have to write it with only the Ruby standard library. This script won’t be something developers work on frequently, so our best approach is to make it explicit and procedural. We’ll create a main method called setup
that performs the actual setup steps.
Get hands-on with 1200+ tech skills courses.