0

I have a scenario where I have to read index.js in my rails controller.

  • index.js is located at device/setup/index.js
  • the controller is located at app/controllers/xxx_controller.rb

Inside controller method, I have to get this index.js and I can't seem to read it with File.open() or File.read(). I tried relative path.

How can I read index.js in my controller?

Nan Da
  • 107
  • 1
  • 4
  • What error did you get when you tried `File.open("device/setup/index.js")` – JP Silvashy Aug 12 '21 at 12:46
  • Does this answer your question? [How to read whole file in Ruby?](https://stackoverflow.com/questions/3328495/how-to-read-whole-file-in-ruby) – Jared Beck Aug 12 '21 at 19:28
  • Reading file is no problem. I could do it after opening the correct file. Thanks to JP Silvashy for providing `Rails.root` solution. It solved my problem of getting to correct file directory. – Nan Da Aug 13 '21 at 01:32

1 Answers1

1

Try using Rails.root to reference the root path of the app:

file = File.open(Rails.root.join('device', 'setup', 'index.js'))
JP Silvashy
  • 46,977
  • 48
  • 149
  • 227