Rails Runner

Some days ago, I came across a requirement where I needed to run some rails code at the end of deployment. We use the Capistrano tool for the deployment, and it has great support for hooks like after 'deploy:published', 'some_task'

Most of the examples show some system commands, since Capistrano is a deployment tool, and isn’t running rails.

But I didn’t know that, being new to rails ecosystem.

So at first, at just called a background job that needed to talk to third party system and get some data, once the rails server is up.

I was met with uninitialized constant error.

After looking around similar scripts in other projects, I came across rails runner (rails r) also works.

It is like rails c, as in it does not run the server, but loads all the rails environment (which is what I wanted) But unlike rails c, it runs the rails code non-interactively.

Couple of examples :

  1. bin/rails runner "Model.long_running_method"
  2. bin/rails runner lib/code_to_be_run.rb
  3. bin/rails runner -e staging "Model.long_running_method" to run it under specific environment.

You can read more in the rails documentation

`