I often find myself spending a lot of time in the Rails console testing out code. As my examples get more complex, I often will create a temporary ruby file to write the script, then copy-paste into the console.
Although this works ok, it is tedious and could be optimized.
Rails runner (rails r) will allow you to run a ruby script within the context of the application environment.
For example, if I had a ruby file named runme.rb
and inside it had some debugging code:
puts Member.count
I could run that script using rails runner runme.rb
. This is nice, but I then have to return to the terminal each time I modify the file. What if we could automate this?
fswatch is a cross-platform file change monitor. It will watch any files you specify, then run a script on change.
Let’s set up a script within our Rails app to run this file automatically when it changes.
Install fswatch
It’s easy to install fswatch. On a mac, you can run
$ brew install fwatch
Set up a watcher script
I created an executable bash script at bin/console-runner
:
#!/bin/bash
usage() {
echo "Watch a ruby script and use Rails runner each time it changes"
echo ""
echo "For example, you may have a file called `runme.rb` that you would"
echo "run using Rails runner (e.g. `rails runner runme.rb`). This script"
echo "will watch the file and run it each time there is a change."
echo ""
echo "Usage:"
echo " ./script/console-runner "
}
if [ $# -eq 0 ]; then
usage
exit 1
else
fswatch -0 -o $1 | xargs -0 -n1 -I{} rails runner $1
fi
Be sure to make the script executable:
$ chmod +x bin/console-runner
We can test the script documentation by running the command:
$ ./bin/console-runner
Watch a ruby script and use Rails runner each time it changes
For example, you may have a file called `runme.rb` that you would
run using Rails runner (e.g. `rails runner runme.rb`). This script
will watch the file and run it each time there is a change.
Usage:
./bin/console-runner
Create your console script to be watched
Next, I created a file in the root folder of my Rails app called runme.rb
.
puts Member.count
puts Rails.env
Run the script
Finally, I can run the script:
./bin/console-runner runme.rb
Success! Now each time I modify runme.rb
, the script will re-run.