Guss
Guss

Reputation: 32354

Load environment settings from a string using Ruby's Dotenv?

I have a ruby system that relies heavily on having run-time settings in the system environment (it uses capistrano 2 a lot, but also for other things), but as I need it to be much more flexible that what loading some static .env files can do for me, I've set up some code that generates environment configurations on the fly.

Currently the only way that I found to use those "dynamic environments" is to save them to a temporary file so that Dotenv.load can read them - which sounds incredibly silly to me.

I've perused the (very limited) Dotenv documentation but there doesn't seem to be a call to get Dotenv to parse a string instead of a file. Any idea how to do that?

Upvotes: 0

Views: 719

Answers (1)

Guss
Guss

Reputation: 32354

After reviewing the source code, I found a solution which just uses the Dotenv parser to read the environment text and convert it to a Hash, which is currently good enough for me as I can feed it to the Capistrano run command as an option:

Dotenv::Parser.call(environment_text)

From there, its trivial to load it into the environment for it to be available to later calls, for example:

Dotenv::Parser.call(environment_text).each { |k,v| ENV[k] = v }

Upvotes: 1

Related Questions