Textfiles are the simplest way to store state across program runs

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the architecture category.

Last Updated: 2023-12-03

If you want to store state (e.g. an oauth access token that changes often) in a way with minimal dependencies and maximum flexibility, what should your library do? Spin up an SQL database? Install firebase?

Answer: It should save a local file on the hard-drive. This is how the Google API for YouTube (below) does things, using an internactive process to persist them into a local YML file it creates and then manages.

(My first instinct would probably have been to copy and paste the token into the code every x hours when it expired -- or just not support any persistence at all.)

def credentials_file
  Rails.root + '.oauth_credentials/youtube.yaml'

# Login 
credentials = get_working_credentials

# When you existing credentials are available or work
if credentials.nil?
  url = authorizer.get_authorization_url(base_url: REDIRECT_URI)
  puts 'Enter the resulting code parameter in the URL after authorization'
  # Open up a browser to handle the oauth process
  # Place code into the program
  code = gets

  # NB: This bit saves the results of the oauth process
  credentials = authorizer.get_and_store_credentials_from_code(
    user_id: user_id, code: code, base_url: redirect_uri

def get_working_credentials
  # check if credentials file is present