Sha256: 2b385973623b73457bff11f90bc87a89a4a7116cf7946863a8062e814fabb594

Contents?: true

Size: 1.53 KB

Versions: 4

Compression:

Stored size: 1.53 KB

Contents

# This class contains the logic to find the user's credentials in either an
# environment variable or a configuration file. If both exist and a
# configuration file has not been specified, the environment variable is
# preferred. If both exist and a config file has been specified, the config
# file is preferred.
#
# The environment varibale is called 'SUMO_CREDS'; the default configuration
# file is '~/.sumo_creds'.
class Sumo::Config
  include Sumo::Error

  attr_reader :config_file

  # Set and freeze the @config_file instance variable.
  def initialize(config_file = Sumo::DEFAULT_CONFIG_FILE)
    if config_file.is_a?(String)
      @config_file = File.expand_path(config_file).freeze
    else
      raise TypeError, "Expected a String, got: #{config_file}"
    end
  end

  # Test if an alternate file has been specified.
  def file_specified?
    config_file != Sumo::DEFAULT_CONFIG_FILE
  end

  # Memoize the credentials from the environment.
  def env_creds
    @env_creds ||= ENV['SUMO_CREDS']
  end

  # Memoize the credentials from the configuration file.
  def file_creds
    @file_creds ||= File.read(config_file).chomp if File.exists?(config_file)
  end

  # Load the credentials.
  def load_config
    if file_specified?
      file_creds || env_creds
    else
      env_creds || file_creds
    end
  end

  # Load the credentials, raising an error if none are specified.
  def load_config!
    if (creds = load_config).nil?
      raise NoCredsFound, "No credentials were found, set ENV['SUMO_CREDS']."
    else
      creds
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
sumo-search-0.1.1 lib/sumo/config.rb
sumo-search-0.1.0 lib/sumo/config.rb
sumo-search-0.0.2 lib/sumo/config.rb
sumo-search-0.0.1 lib/sumo/config.rb