How to load environment variables in the Rails console?
Asked Answered
A

3

34

I think this is a little, easy question!

I'm using .env file to keep all my environment variables, and i'm using foreman.

Unfortunately, these environment variables are not being loaded when running rails console rails c so, i'm now loading them manually after running the console, which is not the best way.

I'd like to know if there any better way for that.

Agent answered 12/3, 2013 at 19:52 Comment(0)
C
68

About a year ago, the "run" command was added to foreman

ref: https://github.com/ddollar/foreman/pull/121

You can use it as follow:

foreman run rails console

or

foreman run rake db:migrate

Chronopher answered 10/6, 2013 at 21:43 Comment(0)
S
2

rails does not know about the environmental variables specified in .env file as it is specific to foreman. You need to set the environment explicitly before invoking rails console. Have a look at this question.

Stenson answered 14/3, 2013 at 7:19 Comment(0)
S
1

I personnaly use dotenv in development and testing environements. With this approach, you don't have to prefix your commands, just call the initializer in your config/application.rb :

Bundler.require(*Rails.groups)

Dotenv::Railtie.load

HOSTNAME = ENV['HOSTNAME']
Snowbird answered 14/6, 2018 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.