staxim
staxim

Reputation: 1467

Why are my environment variables not being loaded properly before initialization code?

I've spent the past couple of days getting redis/resque up and running for my project. I have some code in my initializer that tells Resque the URL of redis to use; this URL is stored in an environment variable. The initialization code is pretty simple:

Resque.redis = Redis.new(url: "#{ENV['REDISTOGO_URL']}")

Now, this code runs fine when I run rails server. It also runs fine when I start the server with foreman (foreman start). However, when I try to run the console it blows up with the following error: gems/redis-3.2.1/lib/redis/client.rb:405:in '_parse_options': invalid uri scheme '' (ArgumentError). I get this error whether I try to run the console by itself (rails console) or with foreman (foreman run rails console).

By process of elimination, I've determined that the error is due to the Resque initalization line above. When I comment it out, the console starts without any problems. The really confusing thing is that when I now execute that line in my working console, it runs fine! After some poking around, it seems that my environment variables are not loaded before the initialization code.

This is a strange one. Any help is much appreciated!

Upvotes: 1

Views: 1259

Answers (1)

staxim
staxim

Reputation: 1467

So, after much digging I've found that this problem is seemingly related to Spring (added to Rails 4.1), which preloads an instance of your app in the background.

What's confusing is that this was only affecting the Rails initializers in my code... after the console is loaded I can access the correct environment variables without any problems.

The 'fix' was rather simple. You simply run spring stop before running the console again. You can also update spring to keep an eye on any of your environment files so that it correctly pre-loads them if they change in the future. See this SO answer for more details on setting up spring to properly watch your env file(s).

Upvotes: 1

Related Questions