module RubyPitaya class Config def initialize() @config = {} @configs_folder_paths = [Path::APP_CONFIG_FOLDER_PATH] + Path::Plugins::APP_CONFIG_FOLDER_PATHS @configs_folder_paths.each do |configs_folder_path| path_to_all_files = File.join(configs_folder_path, '**/*.json') config_files = Dir.glob(path_to_all_files) config_files.each do |config_file| load_config_file(configs_folder_path, config_file) end end end def get @config end def [](key) @config[key] end def auto_reload require 'listen' @configs_folder_paths.each do |configs_folder_path| config_files_listener = Listen.to(configs_folder_path, only: /\.json$/) do |modified, added, removed| import_added_files(configs_folder_path, added) reload_modified_files(configs_folder_path, modified) end config_files_listener.start end end private def load_config_file(configs_folder_path, file_path) config_text = File.open(file_path, &:read) config_hash = JSON.parse(config_text) path_array = file_path.sub(/^#{configs_folder_path}/, '')[0..-6] .split('/') set_config_value(path_array, config_hash) rescue Exception => error puts "ERROR: #{error}" puts error.backtrace end def import_added_files(configs_folder_path, files_path) files_path.each do |path| load_config_file(configs_folder_path, path) puts "ADDED config: #{path}" end end def reload_modified_files(configs_folder_path, files_path) files_path.each do |path| load_config_file(configs_folder_path, path) puts "MODIFIED @config: #{path}" end end def set_config_value(keys, value) config = @config keys.each_with_index do |key, index| is_last_index = index == keys.size - 1 if is_last_index config[key] = value else config[key] = {} unless config.key?(key) config = config[key] end end end end end