Rescue if a YAML file does not exist or cannot load in Rails

I am using a YAML file to store sensitive configuration data. I just use this file in a development environment. In production, I use ENV variables.

Here is what I am doing right now:

I have a config / authorizedal.yml file that looks like this:

email: user_name: 'my_user' password: 'my_passw' 

I have a config / environment / development.rb file that (among other things) has the following lines:

  # Mailer config email_confidential = YAML.load_file("#{Rails.root}/config/confidential.yml")['email'] config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address => "smtp.gmail.com", :port => 587, :domain => 'baci.lindsaar.net', :user_name => email_confidential['user_name'], :password => email_confidential['password'], :authentication => 'plain', :enable_starttls_auto => true } 

My question is: how can I make sure that the YAML file exists and can be loaded, and if I did not select some exception? Where should it be delivered?

+6
source share
2 answers

Why not

 unless File.exists? ("#{Rails.root}/config/confidential.yml") # do what you want (throw exception or something) end 

By the way, I think it is a good idea to put the yaml boot with the configuration in the initializers. for instance

 # config/initializers/load_project_config_file.rb if File.exists? ("#{Rails.root}/config/project.yml") PROJECT = YAML.load_file("#{Rails.root}/config/project.yml") else PROJECT = {} end 
+8
source

The decision made has a race condition: if the configuration file is deleted or moved between File.exists? and YAML.load_file , then the code will fail.

The best solution is to try to open the file first and then recover after the exception:

 begin PROJECT = YAML.load_file("#{Rails.root}/config/project.yml") rescue Errno::ENOENT PROJECT = {} end 
+2
source

Source: https://habr.com/ru/post/943871/


All Articles