Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: difference between ENV.fetch() and ENV[]

What is the difference between these two syntax:

ENV.fetch("MY_VAR")

ENV['MY_VAR']

I've seen Rails 5 use both versions of these in difference places and can't figure out what the difference is (apart from the first one being more characters to type).

like image 221
Winker Avatar asked Dec 27 '17 02:12

Winker


People also ask

What is ENV fetch?

The fetch() method of the ENV class fetches or finds an environment variable. It takes the environment variable's name and returns the value of this environment variable.

What is ENV variable in Ruby?

An environment variable is a key/value pair, it looks like this: KEY=VALUE. 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 ENV in rack?

The env variable is a hash, which contains a lot of useful information including request headers and body, and run-time environment data that may have been added by upstream middleware. Follow this answer to receive notifications.

What is ENV in Ruby on Rails?

The ENV hash in your Rails application is set when your Rails application starts. Rails loads into ENV any environment variables stored in your computer and any other key-value pairs you add using Figaro gem.


1 Answers

The ENV hash-like object is plain Ruby, not part of Rails. From the fine ENV#[] manual:

Retrieves the value for environment variable name as a String. Returns nil if the named variable does not exist.

and the fine ENV#fetch manual:

Retrieves the environment variable name.

If the given name does not exist and neither default nor a block a provided an IndexError is raised. If a block is given it is called with the missing name to provide a value. If a default value is given it will be returned when no block is given.

So just like Hash#[] and Hash#fetch, the only difference is that fetch allows you to specify the behavior if a key is not found (use a default value passed to fetch, default block passed to fetch, or raise an exception) whereas [] just silently gives you nil if the key isn't found.

In the specific case of:

ENV.fetch("MY_VAR") ENV['MY_VAR'] 

the difference is that ENV['MY_VAR'] will give you nil if there is no MY_VAR environment variable but ENV.fetch('MY_VAR') will raise an exception.

like image 122
mu is too short Avatar answered Sep 21 '22 08:09

mu is too short