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?

3
  • What error did you get when you tried File.open("device/setup/index.js") Commented Aug 12, 2021 at 12:46
  • Does this answer your question? How to read whole file in Ruby? Commented Aug 12, 2021 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. Commented Aug 13, 2021 at 1:32

1 Answer 1

1

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

file = File.open(Rails.root.join('device', 'setup', 'index.js'))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks JP Silvashy. Rails.root works like a charm. I can open the file now. Hope it will still work on production server.
Yes this will work on a production server as well! Good Luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.