Sha256: d184884d71780b70ca1c46f593759d922bae58c2d516ed9cb54bc6bc2dd440ee

Contents?: true

Size: 1.66 KB

Versions: 3

Compression:

Stored size: 1.66 KB

Contents

module Chambermaid
  # Environment keeps a set of params available to load into ENV. It also
  # maintains a copy of ENV at the time of its initialization, in order to
  # restore it.
  #
  # @attr_reader [Hash] params
  class Environment < Hash
    attr_reader :params

    # Create new Chambermaid::Environment
    #
    # @param [Hash] params
    #
    # @raise [ArgumentError]
    #   if params is not type Hash
    #
    # @return [Chambermaid::Environment]
    def initialize(params)
      validate_params!(params)
      stash_current_env!
      update(format_env(params))
    end

    # Generate a dotenv (.env) compatible string
    #
    # @return [String] dotenv compatible string
    def to_dotenv
      to_h.inject("") do |env_str, param|
        env_str + "#{param[0]}=#{param[1]}\n"
      end
    end

    # Write a .env file
    #
    # @param [String] file_path
    def to_file!(file_path)
      File.open(file_path, "wb") do |f|
        f.write(to_dotenv)
      end
    end

    # Inject into ENV without overwriting duplicates
    #
    # @return [Hash]
    def load!
      each { |k, v| ENV[k] ||= v }
    end

    # Inject into ENV and overwrite duplicates
    #
    # @return [Hash]
    def overload!
      each { |k, v| ENV[k] = v }
    end

    # Restore to original ENV
    #
    # @return [ENV]
    def unload!
      ENV.replace(@_original_env)
    end

    private

    def stash_current_env!
      @_original_env ||= ENV.to_h.dup.freeze
    end

    def format_env(params)
      params.map{|k,v| [k.upcase, v]}.to_h
    end

    def validate_params!(params)
      unless params.is_a?(Hash)
        raise ArgumentError.new("`params` must be a hash")
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
chambermaid-1.0.1 lib/chambermaid/environment.rb
chambermaid-1.0.0 lib/chambermaid/environment.rb
chambermaid-0.5.5 lib/chambermaid/environment.rb