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.
lib(Rails 6). I don't see the value in loading the entire Rails environment and then discard it for a single command. Could you not just run the whole script viarails runner?Rails runneris an option. In my case, the overhead is not too critical as I need this command just once at startup. I can confirm that the command works from lib/assets. I will try to move my script.require "bundler/setup". This cleans the load path and causes the error when calling Rails runner or Rake tasks from within the script. I will revise the script to have a better integration with Rails. Thanks for the comments and the answer.