Reputation: 95
So I've created a few variables to store API key and secrets in. But I don't understand how I'm supposed to reference those variables in my code. When I try to push up my code to Heroku it says that I have undefined constant variables. Which yes I do. So what do I have to do here?
Upvotes: 0
Views: 112
Reputation: 102036
Heroku's config vars are exposed to your app’s code as environmental variables. In Ruby you can access env vars through the ENV
hash. This is actually just a plain old hash.
You can either use the normal bracket accessors or Hash#key:
ENV['MY_SECRET_KEY'] # string / nil
ENV.key('MY_SECRET_KEY') # string / nil
ENV.key?('MY_SECRET_KEY') # true / false
You can also use Hash#fetch
which lets you either raise an error if the key is missing or provide a default value:
ENV.fetch('MY_SECRET_KEY') # raises a KeyError if the var is not set
ENV.fetch('MY_SECRET_KEY', 'abcd1234') # provides a default value
Raising an error can really help with troubleshooting as it will fail fast and tell you exactly where the problem is.
Upvotes: 3