volx757
volx757

Reputation: 163

Rails environment variables failing to load in model

I have an environment variable that I'm using in two places, one is in a rake task, the other is in a model method. When I call it from the rake task, everything is fine and the variable loads, but when I call it from the model it doesn't find anything. It's not a nil error or any other error, it just returns an empty string.

Is there any reason the environment variables would be overridden or inaccessible to the model?

It's being used to build a url:

http://#{AppEnv['env_var_1']}/this/is/#{AppEnv['env_var_2']}/a/path

--one more thing, myabe it's relevant, the model method is called after_create

EDIT:

thanks for the responses, but my question isn't how to access or use env vars, as you can see I'm already using them above. My question is why they are not loading in my model.

EDIT 2:

I have 4 relevant AppEnv variables, and [this is really weird so bear with me] when I check them on running the rake task (puts all 4 of them to the log), they are as expected. When I run the exact same class method, but called after_create in a model, 3 of the variables are empty, and one of them holds the value of a different variable. That is:

AppEnvVar1 is empty

AppEnvVar2 has the value of AppEnvVar4

AppEnvVar3 is empty

AppEnvVar4 is empty

If I change the method to self.method (allowing me to run it from the console), and run it, it works. So I'm pretty sure I've narrowed this down to an issue with the AppEnv during an after filter. any ideas on where to dig?

Upvotes: 2

Views: 663

Answers (2)

volx757
volx757

Reputation: 163

I restarted the server and everything worked fine. Mysterious...

Upvotes: 0

Topher Hunt
Topher Hunt

Reputation: 4804

Rails sets a global constant hash ENV that should be available anywhere in your app after it's initialized, including in your models. So you should be able to refer to any enviroment variable like this (assuming the relevant env variables has been set):

"http://#{ENV['ROOT_DOMAIN']}/this/is/#{ENV['SECONDARY_DOMAIN']}/a/path"

Upvotes: 1

Related Questions