hanami/lib/hanami/env.rb

66 lines
1.2 KiB
Ruby

begin
require 'dotenv'
rescue LoadError # rubocop:disable Lint/HandleExceptions
end
module Hanami
# Encapsulate access to ENV
#
# @since x.x.x
# @api private
class Env
# Create a new instance
#
# @param env [#[],#[]=] a Hash like object. It defaults to ENV
#
# @return [Hanami::Env]
#
# @since x.x.x
# @api private
def initialize(env: ENV)
@env = env
end
# Return a value, if found
#
# @param key [String] the key
#
# @return [String,NilClass] the value, if found
#
# @since x.x.x
# @api private
def [](key)
@env[key]
end
# Sets a value
#
# @param key [String] the key
# @param value [String] the value
#
# @since x.x.x
# @api private
def []=(key, value)
@env[key] = value
end
# Loads a dotenv file and updates self
#
# @param path [String, Pathname] the path to the dotenv file
#
# @return void
#
# @since x.x.x
# @api private
def load!(path)
return unless defined?(Dotenv)
contents = ::File.open(path, "rb:bom|utf-8", &:read)
parsed = Dotenv::Parser.call(contents)
@env.merge!(parsed)
nil
end
end
end