Class: Credentials

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

Overview

This class provides a way to access application credentials in a Rails application. It allows for nested keys and also checks environment variables if the key is not found in credentials. The keys are expected to be in snake_case format.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.get(key = "", default_value = "") ⇒ ActiveSupport::EncryptedConfiguration, String

This method allows you to retrieve a credential by its key. If the key is not found in the credentials, it will return the default_value. If the key exists in the environment variables, it will return that value instead.

Parameters:

  • key (String) (defaults to: "")

    The key to retrieve from credentials or environment variables.

  • default_value (String) (defaults to: "")

    The value to return if the key is not found in credentials or environment variables.

Returns:

  • (ActiveSupport::EncryptedConfiguration, String)

    The value associated with the key, or an empty string if not found.



14
15
16
# File 'lib/credentials.rb', line 14

def self.get(key = "", default_value = "")
  new.get(key, default_value)
end

Instance Method Details

#get(key = "", default_value) ⇒ ActiveSupport::EncryptedConfiguration, String

Instance method to retrieve a credential by its key. If the key is not found in the credentials, it will return an empty string. If the key exists in the environment variables, it will return that value instead.

Parameters:

  • key (String) (defaults to: "")

    The key to retrieve from credentials or environment variables.

  • default_value (String)

    The value to return if the key is not found in credentials or environment variables.

Returns:

  • (ActiveSupport::EncryptedConfiguration, String)

    The value associated with the key, or the default value if not found.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/credentials.rb', line 24

def get(key = "", default_value)
  return "" if key.blank?
  return ENV[key] if ENV.key?(key)

  keys = key.split("_").map(&:downcase)
  result = credentials
  keys.each do |inner_key|
    result = read_credentials(inner_key, result)
  end

  result.presence || default_value
rescue NoMethodError
  default_value || ""
end