I want to read a .yml file included in a Rails Engine Gem from my main_app. The file is located at config/test.yml
.
IO.read("config/test.yml")
fails with No such file or directory @ rb_sysopen
If i move the file into the main app, everything works fine. But i need this file in a Gem.
Solution 1
You can store the root path in a constant from your main gem file and retrieve it in other locations of your code. You must ensure that the gem got initialized before the code in your app runs otherwise you'll have an errors because the constant won't be defined.
# lib/my_gem.rb
GEM_ROOT = File.expand_path("../..", __FILE__)
# app/.../some_class.rb
IO.read("#{GEM_ROOT}/config/test.yml")
Solution 2
The most advisable, you can get the gem path programmatically from Bundler
, then use that root path to retrieve the full path of your yml file.
Have a look at this answer that you can easily adapt to your case
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With