Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rescue if YAML file doesn't exist or can't load in Rails

I am using a YAML file to store some confidential configuration data. I am just using that file in development environment. In production I am using ENV variables.

Here is what I am doing right now:

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

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

I have a config/environments/development.rb file that (among other stuff) have these 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 could I make sure that the YAML file exists and can be loaded, and if not throw some exception? Where should that be put?

like image 729
Hommer Smith Avatar asked Apr 29 '13 10:04

Hommer Smith


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 this it is a good idea to put loading yaml with configuration to initializers. For example

# 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
like image 56
Danil Speransky Avatar answered Oct 21 '22 17:10

Danil Speransky


The accepted solution has a race condition: if the config file is deleted or moved in between File.exists? and YAML.load_file, then the code will fail.

A better solution is to try opening the file first, then recover from the exception afterward:

begin
  PROJECT = YAML.load_file("#{Rails.root}/config/project.yml")
rescue Errno::ENOENT
  PROJECT = {}
end
like image 45
Lambda Fairy Avatar answered Oct 21 '22 17:10

Lambda Fairy