Run Rails Runner from Ruby Script

1.3k views Asked by At

I have a Ruby script in a subdirectory of a Ruby on Rails application that runs in the background and performs some support tasks. In this script, would like have access to the Rails environment and the value of an application controller constant.

The best approach to retrieve these values I could find so far is based in Rails runner. If I run

cd .. && Rails runner "puts [Rails.env, ApplicationController::CONSTANT_NAME]"

from the subdirectory in shell, I get the desired values. But when I try to use the same command in my script, I get an undefined method error for active_storage:

/home/user/.rvm/gems/ruby-2.6.5/gems/railties-6.0.3.2/lib/rails/railtie/configuration.rb:96:in `method_missing': undefined method `active_storage' for #<Rails::Application::Configuration:0x0000563603fbdaa8> (NoMethodError)

The code in the script is

puts %x|cd .. && rails runner "puts [Rails.env, ApplicationController::CONSTANT_NAME]"|

The Rails application and the Ruby script run under the same user. I have Rails 6.0.3.2 and Ruby 2.6.5.

1

There are 1 answers

2
max On BEST ANSWER

What you want to do is write a Rake task instead:

# lib/tasks/foo.rake
namespace :foo do
  description "@TODO write a descripion"
  task bar: :environment do
    # your logic goes here
    puts [Rails.env, ApplicationController::CONSTANT_NAME]
  end
end

This task can be invoked via bin/rake foo:bar. bar: :environment loads the Rails environment for this task.

This is a lot less hacky/wonky then using the rails runner, and is the defacto way of writing tasks/scripts in Ruby that are meant to invoked from the command line.