Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set environment variable (ENV) for use in Rails

Experimenting with MongoID on a Rails server and confused about how/where to set the environment variables.

config/mongoid.yml default template provides:

defaults: &defaults
  host: localhost

...

# set these environment variables on your prod server
production:
  host: <%= ENV['MONGOID_HOST'] %>
  port: <%= ENV['MONGOID_PORT'] %>
  username: <%= ENV['MONGOID_USERNAME'] %>
  password: <%= ENV['MONGOID_PASSWORD'] %>
  database: <%= ENV['MONGOID_DATABASE'] %>

My question is are these set in Rails somewhere? or are they at the system level? and if so where/how to set so that no user account needs to be logged in for them to be valid?

like image 391
Meltemi Avatar asked Feb 11 '11 20:02

Meltemi


People also ask

How do you use environment variables in Ruby?

Passing Environment Variables to Ruby To pass environment variables to Ruby, simply set that environment variable in the shell. This varies slightly between operating systems, but the concepts remain the same. To set an environment variable on the Windows command prompt, use the set command.

Where are Rails environment variables stored?

Keeping Environment Variables PrivateRemote git repositories such as GitHub are a place to store and share code. If your project is open source, any developer will have access to your code. You don't want to share email account credentials or private API keys with the public.

How do I see environment variables in Rails?

Use command ENV in rails console. That will return a hash of your environmental values you can access. Alternatively, you can access your environmental variables from your apps root path using the same command and the variables will be returned formatted.


1 Answers

The ENV hash will have values from the system environment from when the rails process was started.

These can be set on the command line prior to starting the server or program. For example in bash:

export MONGOID_USERNAME='username'

These are only good for the life of your shell, unless you add them to your profile, but it is likely that your web server won't use that profile, so it is only useful for local development.

They can also be set, for example, in Apache with SetEnv. For example:

<Location /app >
    SetEnv MONGOID_HOST 'localhost'
    SetEnv MONGOID_PORT '8883'
    SetEnv MONGOID_USERNAME 'username'
</Location>

This could be anywhere SetEnv is legal in your apache config, and that is the same context that your application lives under.

Regarding you comment about best practices, some people put an example yml config file in source control, and ignore the config/*.yml files from source control. When cloning a repository, copying and correcting the examples to the correct values is part of the setup, like running rake tmp:create to make the tmp folder structure.

like image 133
danivovich Avatar answered Sep 22 '22 15:09

danivovich