Heroku/Foreman Environment Variables and Rails

18 Jan 2021

The Gist

When working with Ruby on Rails, I’ve usually used figaro or some equivalent gem for handling local environment variables. Recently, I learned that, if I’m planning on deploying to Heroku and I use Heroku CLI or foreman locally, I don’t need to do that

In fact, all I need to do is add a .env file in the root of the directory with my environment variables defined. Then, when I start up foreman, it will automatically load that .env file!

Now, you’ll still need to set those environment variables in your deployment environment using Config Vars, but this makes managing them locally a lot easier, in my opinion

Example Use Case

In order to give you a solid view on what I mean, I’ll provide an example scenario. When using foreman, you may want to throw a debugger line somewhere in your code (using byebug, pry or whichever debugger you prefer. For this example, I’ll use byebug since it’s the default in Rails).

If you want to debug and step through your code from the command line, you cannot simply put a byebug statement in your code and load the page. You’ll get the code to hault execution, but you will not be able to interact with it. That is because the application is not running on the same thread as your console environment, so all you can do is read from that console

Therefore, you will need to start up a byebug server in a seprate console window in order to interact with byebug

The easiest way to do this (in my opinion) is to add a conditional block to a byebug initializer, such as the following:

# config/initializers/byebug.rb

if Rails.env.development? && ENV['BYEBUGPORT']
  require 'byebug/core'
  Byebug.start_server 'localhost', ENV['BYEBUGPORT'].to_i
end

By allowing the port to be set manually, we:

Now, in the .env file, add:

// .env
BYEBUGPORT=3001

In one console, run:

byebug -R localhost:3001

And in another, run:

heroku local -f Procfile.dev

or:

foreman start -f Procfile.dev

In the browser, load the page that will trigger the byebug breakpoint. In the console where you ran the Procfile, you should see that the byebug breakpoint triggered. In the one where you ran the byebug server, you should see the interactive console

Conclusion

I know this was short and simple, but hopefully it helps someone else who has made this harder on themselves than it had to be

References