The danger of Rails.env.production?

BY Doug Breaker

May 08, 2019

Rails Post.png

Updated version of an article first published on March 23rd, 2017.

When I do a code review, one of the scariest things I see is logic like this:

if Rails.env.production?
  do_additional_work
end

Why? Your beautiful tests and tightly integrated CI system won't execute that code. You won't see that code execute as you refresh your browser in development. From syntax errors to misspelled referenced classes, you'll be blind on exceptions...until you deploy to production.

One of the most common places I'll see this is in javascript analytics tracking. For example, you likely don't want to track Google Analytics in development. So, it's easy to do this:

- if Rails.env.production?
  = render partial: 'shared/google_analytics'

However, if that javascript includes some custom Ruby code for handling event tracking, it can easily break in production. For example, lets say we create a custom Ruby Event class to encapsulate an event we wish to track in Google Analytics. We'll send the event to GA if it exists in the session flash:

<% if event=flash[:event] %>
  ga('send', 'event', '<%=event.category%>', '<%=event.action%>');
<% end %>

If we shorted the Event#category method name to Event#cat, rendering the page would generate an exception in production. It's possible that wouldn't be caught in our test or development environments.

Use an alternate API key

To ensure we're testing the full cycle, I'll simply reference an alternate API key in the Google Analytics javascript. You can load these API keys in a number of ways. The quick-and-dirty way:

<% api_key = Rails.env.production? ? "PROD API KEY" : "TEST API KEY" %>
...
ga('create', '<%= api_key %>', 'auto');
...

This ensures the full path will be executed and we won't pollute our production analytics data.

Ready to optimize your site? 

Adding servers can be a band-aid for slow code. Scout APM helps you find and fix your inefficient and costly code. We automatically identify N+1 SQL calls, memory bloat, and other code-related issues so you can spend less time debugging and more time programming. 

Ready to optimize your site? Sign up for a free trial.