Ruby on Rails environment variable for development

2019-07-24 02:46发布

Just a quick question to which I couldn't find an answer on stackoverflow.

If it is easy to have environment variable for staging and production (on heroku for example), how can I set environment variable for my localhost (development environment)? (I am on a mac)

As of today I hardcode my api credential for development environment and I don't feel comfortable with that.

Thanks !

3条回答
Emotional °昔
2楼-- · 2019-07-24 03:09

Environment variables are best placed in your .bash_profile file which lives in your home directory on the Mac: /Users/you/.bash_profile. Open that file and add something like this to the end of it:

export MY_ENV_VAR=my_env_value

or

export MY_ENV_VAR="a string with spaces in it"

export is a shell command that sets environment variables. Your .bash_profile is a bash script that runs every time you open a new shell session (open a terminal window) and therefore your export commands will run and set the env vars.

Then they will be available in the ENV constant when you're in Ruby.

查看更多
太酷不给撩
3楼-- · 2019-07-24 03:10

Edit /Users/your_user_name/.bash_profile and add there:

export RAILS_ENV=development
查看更多
我命由我不由天
4楼-- · 2019-07-24 03:14

Use dotenv is intended to be used in development:

Add your application configuration to your .env file in the root of your project.

S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE

You may also add export in front of each line so you can source the file in bash. in .bashrc

export S3_BUCKET=YOURS3BUCKET
export SECRET_KEY=YOURSECRETKEYGOESHERE

Then access in rails app ENV['S3_BUCKET']

查看更多
登录 后发表回答