Ruby Loading Config (Yaml) File in Same Dir as Source

Ruby loading config (yaml) file in same dir as source

You should get path of the current file by:

cnf = YAML::load_file(File.join(File.dirname(File.expand_path(__FILE__)), 'config.yml'))

EDIT:

Since Ruby 2.0 you can simplify that and use:

cnf = YAML::load_file(File.join(__dir__, 'config.yml'))

YAML.load_file issue

I suppose both files are in the same directory but you are not launching the rb file from that directory. If I'm correct try this as well

got_data_1 = YAML.load_file(File.join(File.dirname(__FILE__), 'bestiary.yml'))

This work just if the yml file is in the same directory AND you launch the rb file from that directory also

got_data_1 = YAML.load_file('bestiary.yml')

yml file exists but rails server and passenger complains that it doesn't

Answer is here: Why is my Rails.root nil?

The Application object does not exist yet, so Rails.root returns nil. Try putting the YAML config stuff in an initializer, like RB recommends.

How can I include a YAML file inside another?

No, standard YAML does not include any kind of "import" or "include" statement.

Rails 4 - Yaml configuration file

If you are using Rails 4.2 or higher, you can use config_for for the config files. They need to be placed under /config folder. (haven't tried otherwise)

In your case it would be: config = Rails.application.config_for(:application)

This is more clear and Rails way to load configs into application.

Then you can use OpenStruct to have dot notation enabled for it.

APP_CONFIG = OpenStruct.new(config)



Related Topics



Leave a reply



Submit