Meltemi
Meltemi

Reputation: 38359

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?

Upvotes: 15

Views: 11368

Answers (2)

hayesgm
hayesgm

Reputation: 9096

I wanted to add another option here. On boot, Rails will attempt to read DATABASE_URL as a url and connect to a database from that env variable (ignoring database.yml). You should specify the database as:

DATABASE_URL="mysql2://user:pass@localhost/app_development" rails server

and you can verify this via:

DATABASE_URL="..." rails runner "p ActiveRecord::Base.connection_config"

This is just another option instead of putting erb settings into database.yml.

Upvotes: 0

danivovich
danivovich

Reputation: 4217

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.

Upvotes: 16

Related Questions