Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, which exception is best to handle unset environment variables?

The script I wrote runs at start up and requires that an environment variable be set, but which of Ruby's Exceptions, is best? I used LoadError, I just want to be as descriptive as possible and follow the proper conventions.

Secondly, I can't find another way to see if an environment variable is set besides checking it's length, but that doesn't seem so elegant.

begin
  raise LoadError if ENV['FOO'].to_s.length == 0
  system "open http://example.com/" + ENV['FOO']
rescue Exception => e
  puts "=> #{e} FOO environment variable not set"
end
like image 236
JP Silvashy Avatar asked Aug 12 '12 00:08

JP Silvashy


People also ask

What is an environment variable in Ruby?

An environment variable is a key/value pair, it looks like this: We use these variables to share configuration options between all the programs in your computer. That’s why it’s important to learn how they work & how to access them from your Ruby programs using the ENV special variable.

What is the use of exceptions in Ruby?

The program stops if an exception occurs. So exceptions are used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely. Ruby provide a nice mechanism to handle exceptions.

What is a closed environment in Ruby?

Closed environment, changing variables inside a process (your Ruby program is a process) doesn't change the environment variables outside the process

How to change the path to the ruby environment?

Then click on Advanced System Setting option then under Advanced tab click on Environment Variables. Now, we have to Edit the “Path” variable under System variables so that it also contains the path to the Ruby environment.


1 Answers

You can do something like:

ENV['SECRET_KEY_XXYY'] || raise('no SECRET_KEY_XXYY provided')
like image 99
Dorian Avatar answered Oct 22 '22 18:10

Dorian