Ruby Basics : Setting Environment variables

Objective


To learn about setting environment variables in your projects.

Steps


Step 1

You can set the environment variable in a terminal like this:

$export JUNK='test'

Step 2

In irb, you can read the value like this:

ENV['JUNK']

Step 3

Don't check for nil for the existence of environment variables.

ENV['JUNK'].nil?

Step 4

Check for the existence of the key in ENV hash like this:

ENV.has_key?('JUNK')

Step 5

This makes your conditionals in yml files easier to read. So instead of doing this:

ENV['JUNK'].nil?? ENV['JUNK'] : 'dev'

You can do:

ENV.has_key?('JUNK')? ENV['JUNK'] : 'dev'

This also prevents nil exceptions in your code.

Step 6

Setting environment variable values in a terminal will only last for that session. If you want to set it permanently for your production VPS, you need to add :

export SECRET_API_KEY='very secret'

to the ~/.profile file.

Summary


In this article you learned how to set environment variables properly in your projects.


Related Articles


Create your own user feedback survey