Running rails runner with some parameters Running rails runner with some parameters bash bash

Running rails runner with some parameters


script/runner doesn't take a path to a file, instead it takes some Ruby that it will execute:

script/runner "MyClass.do_something('my_arg')"

You can always set the Rails environment using an environment variable, for example:

RAILS_ENV=production script/runner "MyClass.do_something('my_arg')"

If you want to run some complex task, you may be better off writing it as a Rake task. For example, you could create the file lib/tasks/foo.rake:

namespace :foo do  desc 'Here is a description of my task'  task :bar => :environment do    # Your code here  endend

You would execute this with:

rake foo:bar

And as with script/runner you can set the environment using an environment variable:

RAILS_ENV=production rake foo:bar

It's also possible to pass arguments to a Rake task.


I assume you're on an older Rails based on script/runner I don't know if this works for older Rails' or not, but in newer Rails, you can just require 'config/environment', and it will load the app. Then you can just write your scripts in there.

For example, I have a script that takes an argument, prints it out if it was provided, and then prints out how many users are in my app:

File: app/jobs/my_job.rb

require 'optparse'parser = OptionParser.new do |options|  options.on '-t', '--the-arg SOME_ARG', 'Shows that we can take an arg' do |arg|    puts "THE ARGUMENT WAS #{arg.inspect}"  endendparser.parse! ARGVrequire_relative '../../config/environment'puts "THERE ARE #{User.count} USERS" # I have a users model

Calling with no args:

$ be ruby app/jobs/my_job.rb THERE ARE 2 USERS

Calling with an arg shorthand:

$ be ruby app/jobs/my_job.rb -t my_argTHE ARGUMENT WAS "my_arg"THERE ARE 2 USERS

Calling with an arg long-hand:

$ be ruby app/jobs/my_job.rb --the-arg my_argTHE ARGUMENT WAS "my_arg"THERE ARE 2 USERS


Simply use the below syntax:

rails runner <.rb file path> [..args]

Use ARGV which is an array in your .rb to read the arguments.