bkeepers / dotenv

A Ruby gem to load environment variables from `.env`.
MIT License
6.61k stars 505 forks source link

Handle thread safety for Dotenv.restore, Add Dotenv.modify #475

Closed bkeepers closed 10 months ago

bkeepers commented 10 months ago

This fixes an issue with #472 when running Rails tests with parallelize. Since ENV is global state, modifications are not thread safe. This will raise an error if calling Dotenv.restore outside of Thread.main, and adds Dotenv.modify for a threadsafe way to modify ENV.

Dotenv.modify(MYVAR: "new value") do
  assert_equal "new value", ENV["MYVAR"]
end

Note that the block passed to #modify is synchronized in a semaphore, so threads calling it will execute serially.

This PR also refactors Dotenv::Diff introduced in #473 and uses it to save/restore.