Skip to content

Instantly share code, notes, and snippets.

@matisojka
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matisojka/47e2f78b81280faaa46a to your computer and use it in GitHub Desktop.
Save matisojka/47e2f78b81280faaa46a to your computer and use it in GitHub Desktop.
Proposal for better ENV usage in Ruby
# Currently, many times we are using ENV variables in a non-optimal way.
# I'd like to explain some of the common use cases for those variables
# and how we can use them in a way that we get the most out of it.
# A common error is to assume that the variable has to be there, but it isn't
# This happens when we use the ENV hash like this:
ENV['SOME_KEY']
# In Ruby, if the key is missing, it will return `nil`, thus calling a method on it
# will throw a rather obscure error like this:
`undefined method 'to_i' for nil:NilClass`
# This is not good and will often hide the real issue - which is the variable missing.
# Here are some use cases and how the variables should be fetched
# Use case 1 - mandatory variable
# Often times, an ENV variable needs to be present because no default can be assumed.
# In those cases, we will use the following pattern:
ENV.fetch('MANDATORY_KEY')
# If the key is missing, `Hash#fetch` will throw an error like this:
`KeyError: key not found: MANDATORY_KEY`
# This is pretty revealing about the missing variable and helps find the cause of the failure immediately.
# Use case 2 - optional variable
# This one is pretty straight-forward and can be written like this:
ENV['OPTIONAL_VARIABLE']
# Just remember that the variable will return `nil` if the key is not present.
# Use case 3 - variable with default value
# It's often convenient to provide values that can be overriden.
# For those we can use the following two approaches:
ENV.fetch('IMPORTANT_VARIABLE', 'default fallback')
# or
ENV['IMPORTANT_VARIABLE'] || 'default fallback'
# Both are OK, `#fetch` is maybe a bit more expressive and allows for easier chaining,
# but the piped-or `||` is usually better known by Ruby devs
# Related stuff
# Environment specific values
# Using Rails.env.production? and others might be considered an anti-pattern.
# Often times, it is just easier to define an environment variable and set it
# different on each environment.
# Naming of ENV variables
# It is important to remember that the convention on ENV variable names is to
# use all-caps, in order to distinguish them from other kinds of values.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment