Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dotenviable: Load env into another hash #13

Merged
merged 1 commit into from
Apr 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions lib/appydays/dotenviable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@
# it won't get used, because .env files don't stomp what is already in the environment
# (we don't want to use `overload`).
# So we have some trickery to overwrite only PORT.
#
# @param rack_env [nil,String] Value like 'development' or 'production' to use to load .env files.
# If not given, use +env['RACK_ENV']+ or +default_rack_env+.
# @param default_rack_env [String] If +env['RACK_ENV']+ is not set, use this value.
# @param env [Hash] Hash to read and mutate.
# Pass in a different hash to load environment variables into it instead of ENV.
# Useful for testing, or to get the config for another environment.
module Appydays::Dotenviable
def self.load(rack_env: nil, default_rack_env: "development", env: ENV)
original_port = env.delete("PORT")
Expand All @@ -33,7 +40,17 @@ def self.load(rack_env: nil, default_rack_env: "development", env: ENV)
".env.#{rack_env}",
".env",
]
orig_env = nil
if env.object_id != ENV.object_id
orig_env = ENV.to_h
ENV.replace(env)
end
Dotenv.load(*paths)
if orig_env
env.merge!(ENV)
ENV.replace(orig_env)
end

env["PORT"] ||= original_port
env["RACK_ENV"] ||= rack_env
end
Expand Down
14 changes: 14 additions & 0 deletions spec/appydays/dotenviable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,18 @@
described_class.load(env: env)
expect(env).to include("PORT" => "456")
end

it "can load into a separate hash" do
ENV["HASHTESTABC"] = "x"
File.write(".env.hashtest", "HASHTESTXYZ=a")
e = {}
described_class.load(rack_env: "hashtest", env: e)
expect(e).to include("HASHTESTXYZ" => "a")
expect(e).to_not include("HASHTESTABC")
expect(ENV.to_h).to_not include("HASHTESTXYZ")
expect(ENV.to_h).to include("HASHTESTABC" => "x")
ensure
File.delete(".env.hashtest")
ENV.delete("HASHTESTABC")
end
end
Loading