DEV Community

Eric Berry
Eric Berry

Posted on

Build a Rails script watcher/runner using fswatch

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 <ruby-script>"
}

if [ $# -eq 0 ]; then
    usage
    exit 1
else
  fswatch -0 -o $1 | xargs -0 -n1 -I{} rails runner $1
fi
Enter fullscreen mode Exit fullscreen mode

Be sure to make the script executable:

$ chmod +x bin/console-runner
Enter fullscreen mode Exit fullscreen mode

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 <ruby-script>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Run the script

Finally, I can run the script:

./bin/console-runner runme.rb
Enter fullscreen mode Exit fullscreen mode

Success! Now each time I modify runme.rb, the script will re-run.

Top comments (1)

Collapse
 
igorkasyanchuk profile image
Igor Kasyanchuk

cool idea