syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Rails how do I run a Ruby script with the Rails environment loaded?
Tags: rails ruby runner

Recently I encountered a use-case where I wanted to run a simple Ruby script which had access to a Rails environment.

I can use rails runner to run ruby scripts with a full rails environment loaded into the interpreter.

Here is a screendump of me using rails runner:
dan@hp ~/x611 $ bin/rails runner script/hamlposts2questions.rb
"hello"
dan@hp ~/x611 $
Also I can use a command line option to specify that I want the script to run in the Rails production environment:
dan@hp ~/x611 $ bin/rails runner -e production script/hamlposts2questions.rb
"hello"
dan@hp ~/x611 $

Rails runner is a useful feature of Rails.

One lesson I learned from the school of hard knocks is that I need to be careful about where I place adhoc Ruby scripts. Rails is designed to load any scripts it finds in some directories. So, if I place an adhoc script in Rails.root/controllers, it will get loaded and thus run when I don't want it to run.

The convention I established for myself is to create a directory called script under Rails.root and then place adhoc Ruby scripts in that directory.


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me