dotenv but 3 lines of ruby

github logo Updated on ・1 min read

edit: Thanks to Ben Curtis for inspiring me to cut this from 7 lines to 3.

Make an executable file with the following contents:

#!/usr/bin/env ruby

regexp = /^(\w+)=['"]?(.+?)['"]?$/

ENV.update File.read(".env").scan(regexp).to_h if File.exist?(".env")
exec(ENV, *ARGV)

Make an alias. Here is one with bundle exec also included.

alias be="/path/to/executable bundle exec"

Make an .env file.

echo HELLO=WORLD > .env

Run be bash -c 'echo $HELLO'

twitter logo DISCUSS (3)
markdown guide
 

This is great! Here's an alternative to the 2 lines of code in the loop:

    ENV.update l.chomp.scan(/^(?:export )?(\w+)\s*=\s*(?:['"])?([^'"]+)/i).to_h

This change also handles .env files that have lines in the format of export FOO=bar.

 

How about 3 lines or fairly readable ruby?

#!/usr/bin/env ruby

regexp = /^(\w+)=['"]?(.+?)['"]?$/

ENV.update File.read(".env").scan(regexp).to_h if File.exist?(".env")
exec(ENV, *ARGV)
 

Nice!

I will personally leave out the export stuff because I don't actually need to be compatible with dotenv, but it would be nice for people who do.

Classic DEV Post from Jun 27

Jack Of All Trades or Master of One?

That age old question: how many pies should one have a thumb in?

Kelly Stannard profile image
Developer. Design pattern enthusiast. Tilting at Agile practices.
Join dev.to

Be a better developer. Free forever.