Hommer Smith
Hommer Smith

Reputation: 27852

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?

Upvotes: 7

Views: 5630

Answers (2)

Lambda Fairy
Lambda Fairy

Reputation: 14686

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

Upvotes: 8

Danil Speransky
Danil Speransky

Reputation: 30453

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

Upvotes: 10

Related Questions