Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read files (.yml) from a Gem

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.

like image 531
antpaw Avatar asked Dec 25 '22 06:12

antpaw


1 Answers

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

like image 162
Benj Avatar answered Dec 29 '22 10:12

Benj