We write scripts to automate setup and deployment of Rails applications.
In those scripts, in many places, we need to run system commands like
bundle install, rake db:create, rake db:migrate and many more.
Let’s suppose we need to run migrations using
rake db:migrate in a Rails project setup script.
We can use the Kernel#system method.
Executing system returns true or false.
Another feature of system is that it eats up the exceptions.
Let’s suppose our migrations can run successfully. In this case the system command
for running migrations will return true.
Let’s suppose we have a migration that is trying to add a column to a table which
does not exist. In this case, the system command for running migrations will return
As we can see, even when there is a failure in executing system commands, the return
value is false. Ruby does not raise an exception in those cases.
However, we can use raise explicitly to raise an exception and halt the setup
Ruby 2.6 make our lives easier by providing an option exception: true so that
we do not need to use raise explicitly to halt script execution.
Ruby 2.6 works the same way as previous Ruby versions when used
without the exception option or used with exception set as false.
system is not the only way to execute scripts like these.
We wrote a blog
6 years ago which discusses the differences between running commands using
backtick, exec, sh, popen3, popen2e and Process.spawn.
The Chinese version of this blog is available