class Dotenv::Diff

A diff between multiple states of ENV.

Attributes

a[R]

The initial state

b[R]

The final or current state

Public Class Methods

new(a: snapshot, b: ENV, &block) click to toggle source

Create a new diff. If given a block, the state of ENV after the block will be preserved as the final state for comparison. Otherwise, the current ENV will be the final state.

@param a [Hash] the initial state, defaults to a snapshot of current ENV @param b [Hash] the final state, defaults to the current ENV @yield [diff] a block to execute before recording the final state

# File lib/dotenv/diff.rb, line 16
def initialize(a: snapshot, b: ENV, &block)
  @a, @b = a, b
  block&.call self
ensure
  @b = snapshot if block
end

Public Instance Methods

added() click to toggle source

Return a Hash of keys added with their new values

# File lib/dotenv/diff.rb, line 24
def added
  b.slice(*(b.keys - a.keys))
end
any?() click to toggle source

Returns true if any keys were added, removed, or changed

# File lib/dotenv/diff.rb, line 46
def any?
  [added, removed, changed].any?(&:any?)
end
changed() click to toggle source

Returns of Hash of keys changed with an array of their previous and new values

# File lib/dotenv/diff.rb, line 34
def changed
  (b.slice(*a.keys).to_a - a.to_a).map do |(k, v)|
    [k, [a[k], v]]
  end.to_h
end
env() click to toggle source

Returns a Hash of all added, changed, and removed keys and their new values

# File lib/dotenv/diff.rb, line 41
def env
  b.slice(*(added.keys + changed.keys)).merge(removed.transform_values { |v| nil })
end
removed() click to toggle source

Returns a Hash of keys removed with their previous values

# File lib/dotenv/diff.rb, line 29
def removed
  a.slice(*(a.keys - b.keys))
end

Private Instance Methods

snapshot() click to toggle source
# File lib/dotenv/diff.rb, line 52
def snapshot
  # `dup` should not be required here, but some people use `stub_const` to replace ENV with
  # a `Hash`. This ensures that we get a frozen copy of that instead of freezing the original.
  # https://github.com/bkeepers/dotenv/issues/482
  ENV.to_h.dup.freeze
end