Last Updated: February 25, 2016
·
4.251K
· joefiorini

Access Rails App from Plain Ruby Script

I just wrote a quick benchmark script to get some performance numbers on a model. It's just a plain Ruby script that starts by creating a bunch of models. In order to access the models, I have to run this script in the context of my Rails environment. In the past I've always used ugly require code, but today I learned a new way to do it:

rails runner script/my_cool_script.rb

Or, for the Rails savvy, you can just use rails r.

Wouldn't it be great if we didn't have to prefix it with rails runner every time? Maybe running like a normal script like:

./script/my_cool_script.rb

Well, that requires a shebang line in your script. Usually we make that /usr/bin/env ruby, but what if we change it to /usr/bin/env/rails r?

Voila! So our final script looks like:

#!/usr/bin/env/rails r

# Put your script code here!

Enjoy!

1 Response
Add your response

I've always felt accomplishing loading Rails from a shell script was ugly too. I've always known about Rails runner command but never thought of putting into shebang line. I wonder if that is something new in Rails or if Rails runner has always been compatible with doing that. Very cool.

over 1 year ago ·