Class: Dev::Env
Overview
Class instance represents a ‘.env’ file and includes methods to read/write the given filename
Instance Attribute Summary collapse
-
#data ⇒ Object
Returns the value of attribute data.
-
#envfile ⇒ Object
Returns the value of attribute envfile.
Instance Method Summary collapse
- #containerized? ⇒ Boolean
-
#get(key) ⇒ Object
Get the value of the key from the loaded env data.
-
#initialize(filename = '.env') ⇒ Env
constructor
A new instance of Env.
- #on_host ⇒ Object
-
#set(key, value) ⇒ Object
Set the value of the key in the loaded env data.
-
#write ⇒ Object
Write the current env data back to the original file.
Constructor Details
#initialize(filename = '.env') ⇒ Env
Returns a new instance of Env.
8 9 10 11 12 13 14 15 16 17 |
# File 'lib/firespring_dev_commands/env.rb', line 8 def initialize(filename = '.env') @envfile = Pathname.new(filename) @data = {} return unless File.exist?(@envfile) File.readlines(@envfile).each do |line| key, value = line.split('=') @data[key.to_s.strip.to_sym] = value.to_s.strip end end |
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
6 7 8 |
# File 'lib/firespring_dev_commands/env.rb', line 6 def data @data end |
#envfile ⇒ Object
Returns the value of attribute envfile.
6 7 8 |
# File 'lib/firespring_dev_commands/env.rb', line 6 def envfile @envfile end |
Instance Method Details
#containerized? ⇒ Boolean
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/firespring_dev_commands/env.rb', line 38 def containerized? # Fast path: common flags files return true if File.exist?('/.dockerenv') # Docker return true if File.exist?('/run/.containerenv') # Podman / some runtimes # Env flags some images set return true if ENV['DOCKER_CONTAINER'] == 'true' return true if ENV['container']&.match?(/docker|podman|lxc|containerd/i) # cgroup hints (docker, containerd, kubernetes, podman) %w(/proc/1/cgroup /proc/self/cgroup).any? do |p| next false unless File.readable?(p) File.read(p).match?(/docker|containerd|kubepods|podman|libpod/i) end rescue false end |
#get(key) ⇒ Object
Get the value of the key from the loaded env data
20 21 22 |
# File 'lib/firespring_dev_commands/env.rb', line 20 def get(key) data[key.to_s.strip.to_sym] end |
#on_host ⇒ Object
57 58 59 |
# File 'lib/firespring_dev_commands/env.rb', line 57 def on_host yield unless containerized? end |
#set(key, value) ⇒ Object
Set the value of the key in the loaded env data
25 26 27 |
# File 'lib/firespring_dev_commands/env.rb', line 25 def set(key, value) data[key.to_s.strip.to_sym] = value.to_s.strip end |
#write ⇒ Object
Write the current env data back to the original file
30 31 32 33 34 35 36 |
# File 'lib/firespring_dev_commands/env.rb', line 30 def write File.open(envfile, 'w') do |file| data.each do |key, value| file.write("#{key}=#{value}\n") end end end |