Sha256: d632ace4f569be2edd7f3a59c0b36f72f1025bfa274fe768509434c7eecc957e

Contents?: true

Size: 1.39 KB

Versions: 6

Compression:

Stored size: 1.39 KB

Contents

module Chambermaid
  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
    def load!
      each { |k, v| ENV[k] ||= v }
    end

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

    # Restore to original 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

6 entries across 6 versions & 1 rubygems

Version Path
chambermaid-0.5.4 lib/chambermaid/environment.rb
chambermaid-0.4.1 lib/chambermaid/environment.rb
chambermaid-0.4.0 lib/chambermaid/environment.rb
chambermaid-0.3.2 lib/chambermaid/environment.rb
chambermaid-0.3.1 lib/chambermaid/environment.rb
chambermaid-0.3.0 lib/chambermaid/environment.rb