简体   繁体   中英

Rails.root - uninitialized constant

I am writing a script located in /bin of a rails 5 project. Basically I am trying to iterate through various files and paths. Something to help me with this effort is Rails.root so I don't have to worry about relative paths etc

The problem is, when I am attempting to use Rails.root in my script, I am getting an error:

uninitialized constant Rails (NameError)

My script looks something like this

bin/my_class.rb

class MyClass
  def initialize
    ...
  end

  def my_function
    ...
    Rails.root.to_s
  end 
end

MyClass.new.my_function

Then i call my script like

ruby bin/template_check.rb foo=bar

And it's breaking on the line where I am calling Rails.root with the error message:

uninitialized constant Rails (NameError)

I have tried

  • moving Rails.root to a constant above the class (thought maybe it was a name conflict or something?). didn't work
  • changing the name to ::Rails.root.to_s . did not work either

Does anyone know why I cannot access Rails.root inside of my script?

edit I was able to get this resolved by adding

require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))

to the top of my script. This loads rails. as a default, the script is slower, and I'm not a huge fan of loading all of rails just to use Rails.root , but for now it works.

Other solutions like the answers below are to either use rails runner to run the script, or to wrap everything in a rake task.

Run with $ rails runner bin/my_class.rb . You can find out more about rails runner here

You can try with

rails r bin/my_class.rb  if your file is under bin

other wise you can use

rails r #{file_name}.rb specify the file name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM