Sha256: 1c01b3b12e442a89872e9d6a3d38712e1ae59f6b0d6c3955cfb17d82ee8b113d

Contents?: true

Size: 982 Bytes

Versions: 1

Compression:

Stored size: 982 Bytes

Contents

require "climate_control/errors"
require "climate_control/version"
require "monitor"

module ClimateControl
  extend self

  SEMAPHORE = Monitor.new
  private_constant :SEMAPHORE

  def modify(environment_overrides = {}, &block)
    environment_overrides = environment_overrides.transform_keys(&:to_s)

    SEMAPHORE.synchronize do
      previous = ENV.to_hash

      begin
        copy environment_overrides
      ensure
        middle = ENV.to_hash
      end

      block.call
    ensure
      after = ENV
      (previous.keys | middle.keys | after.keys).each do |key|
        if previous[key] != after[key] && middle[key] == after[key]
          ENV[key] = previous[key]
        end
      end
    end
  end

  def env
    ENV
  end

  private

  def copy(overrides)
    overrides.each do |key, value|
      ENV[key] = value
    rescue TypeError => e
      raise UnassignableValueError,
        "attempted to assign #{value} to #{key} but failed (#{e.message})"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
climate_control-1.1.1 lib/climate_control.rb