Class: Dry::Credentials::Helpers

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/credentials/helpers.rb

Instance Method Summary collapse

Constructor Details

#initialize(extension, env = nil) ⇒ Helpers

Helpers wrapped in a separate class in order not to pollute the extension with methods that could collide with credentials

Parameters:

  • extension (Dry::Credentials::Extension)

    extension using the helpers

  • env (String, nil) (defaults to: nil)

    overrides env setting



12
13
14
15
# File 'lib/dry/credentials/helpers.rb', line 12

def initialize(extension, env=nil)
  @extension = extension
  @env = env || extension[:env]
end

Instance Method Details

#create?Boolean

Whether a new encrypted file will be created

Returns:

  • (Boolean)


60
61
62
# File 'lib/dry/credentials/helpers.rb', line 60

def create?
  !encrypted_file.exist?
end

#edit_yaml(yaml) ⇒ String

Open the given YAML in the preferred editor

Parameters:

  • yaml (String)

    YAML content to edit

Returns:

  • (String)

    edited YAML content



36
37
38
39
40
41
42
43
# File 'lib/dry/credentials/helpers.rb', line 36

def edit_yaml(yaml)
  Tempfile.create('dryc') do |tempfile|
    tempfile.write yaml
    tempfile.close
    system %Q(#{ENV['EDITOR']} "#{tempfile.path}")
    File.read(tempfile.path)
  end
end

#key_evString

Name of the environment variable holding the key

Returns:

  • (String)


67
68
69
70
# File 'lib/dry/credentials/helpers.rb', line 67

def key_ev
  fail Dry::Credentials::EnvNotSetError unless @env
  "#{@env.upcase}_CREDENTIALS_KEY"
end

#read_yamlString

Read the encrypted file and return the decrypted YAML content

Returns:

  • (String)

    YAML content



20
21
22
23
# File 'lib/dry/credentials/helpers.rb', line 20

def read_yaml
  return '' if create?
  encryptor.decrypt(encrypted_file.read, key: key)
end

#write_yaml(yaml) ⇒ Object

Write the decrypted YAML content to the encrypted file

Parameters:

  • yaml (String)

    YAML content



28
29
30
# File 'lib/dry/credentials/helpers.rb', line 28

def write_yaml(yaml)
  encrypted_file.write(encryptor.encrypt(yaml, key: key))
end

#yaml_valid?(yaml) ⇒ Boolean

Whether the YAML content can be read

Parameters:

  • yaml (String)

    YAML content

Returns:

  • (Boolean)


49
50
51
52
53
54
55
# File 'lib/dry/credentials/helpers.rb', line 49

def yaml_valid?(yaml)
  Dry::Credentials::YAML.new(yaml)
  true
rescue Dry::Credentials::YAMLFormatError, Psych::SyntaxError => error
  warn "WARNING: #{error.message}"
  false
end