Class: EncryptedSettings

Inherits:
Object
  • Object
show all
Defined in:
lib/encrypted_settings.rb

Constant Summary collapse

KEY_FILE_PATH =
".settings_encryption_key"

Instance Method Summary collapse

Constructor Details

#initialize(env, editor: ENV["EDITOR"], key: nil) ⇒ EncryptedSettings

Returns a new instance of EncryptedSettings.



19
20
21
22
23
24
25
26
27
28
# File 'lib/encrypted_settings.rb', line 19

def initialize(env, editor: ENV["EDITOR"], key: nil)
  key ||= ENV["SETTINGS_ENCRYPTION_KEY"]
  key = File.read(KEY_FILE_PATH).strip if key.nil? && File.exist?(KEY_FILE_PATH)
  raise "Invalid Encryption Key" if key.nil? || key.length != 32

  @key = key
  @editor = editor || "sub --wait"

  @settings_path = "config/settings_#{env}.yml.enc"
end

Instance Method Details

#editObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/encrypted_settings.rb', line 38

def edit
  # TODO: refactor into a few smaller methods.
  FileUtils.mkdir_p("config")
  content = ""
  content = File.binread(settings_path) if File.exist?(settings_path)
  tmp = Tempfile.new(["settings", ".yml"])
  tmp.rewind
  tmp.write(YAML.safe_load(decrypt(content)).to_yaml) unless content.empty?
  tmp.close
  system("#{editor} #{tmp.path}")

  File.unlink(settings_path) if File.exist?(settings_path)

  File.binwrite(settings_path, encrypt(File.read(tmp.path)))

  tmp.unlink
end

#readObject



30
31
32
33
34
35
36
# File 'lib/encrypted_settings.rb', line 30

def read
  File.binread(settings_path)
    .then(&self.method(:decrypt))
    .then(&YAML.method(:load))
    .then(&JSON.method(:dump))
    .then { |config| JSON.parse(config, object_class: OpenStruct) }
end