# frozen_string_literal: true require 'json' require 'singleton' module ProtoConfig class ConfigManager include Singleton attr_reader :recently_connected_time, :listen_ip, :listen_port, :db_type, :db_params, :db_username, :db_password def initialize # Initialize with default settings @recently_connected_time = 120 # default value @listen_ip = '0.0.0.0' # default value @listen_port = 3080 # default value @db_type = 'sqlite' @db_params = { username: nil, password: nil } # default value # Check if the config file exists in the current working directory config_path = 'config.json' create_default_config(config_path) unless File.exist?(config_path) load_config(config_path) end def create_default_config(config_path) default_config = { 'recently_connected_time' => @recently_connected_time, 'listen_ip' => @listen_ip, 'listen_port' => @listen_port, 'db_type' => @db_type, 'db_params' => @db_params, 'db_username' => @db_username, 'db_password' => @db_password } File.write(config_path, JSON.pretty_generate(default_config)) end def load_config(config_path) # Load configuration from a JSON file config_data = JSON.parse(File.read(config_path)) @recently_connected_time = config_data['recently_connected_time'] if config_data['recently_connected_time'] @listen_ip = config_data['listen_ip'] if config_data['listen_ip'] @listen_port = config_data['listen_port'] if config_data['listen_port'] @db_type = config_data['db_type'] if config_data['db_type'] @db_params = config_data['db_params'] if config_data['db_params'] rescue StandardError => e puts "Failed to load configuration: #{e.message}" end end end