Config class + Json file

Post

Posted
Rating:
#1 (In Topic #680)
Avatar
Regular
tincho is in the usergroup ‘Regular’
Hello friends.
I would like to present you a method to manage the configuration of a program, which I find interesting.
Together with TercoIDE we prepared this example in which in a class there are all the parameters of a program and with great flexibility can be added more. Then in any other part of the program you can read and write those variables.
Finally there is a method (Save) that goes through the symbols of the class and saves them in a text file in json format for future use by retrieving this data with the "Load" method.
Please feel free to give your opinion, comment or improve this program.
Config.class

Code (gambas)

  1. ' Gambas class file
  2. Private Const ConfigFile As String = ".app/config.json"
  3. ''Configuration variables to be saved, add as needed below
  4. Public CurrentColor As Byte = 1
  5. Public CurrentWidth As Byte = 1
  6. Public CurrentLType As Byte = 1
  7. Public OtherParameter1 As String = "gambas-es.org"
  8. Public OtherParameter2 As String = "gambas.one"
  9. Public OtherParameter3 As String = "gambas-club.de"
  10. Public OtherParameter4 As String = "gambas-it.org"
  11.  
  12.  
  13.   Dim jConfig As Collection
  14.   Dim sSymbol As String
  15.   Dim obj As Object = Me
  16.   Dim MyClass As Class = Object.Class(obj)
  17.  
  18.   If sFile = "" Then
  19.     sFile = User.Home &/ ConfigFile
  20.  
  21.   If Exist(sFile) Then
  22.     jConfig = JSON.FromString(File.Load(sFile))
  23.     For Each sSymbol In myClass.Symbols
  24.       If jConfig.Exist(sSymbol) Then
  25.         Object.SetProperty(obj, sSymbol, jConfig[sSymbol])
  26.       Endif
  27.     Next
  28.  
  29.   Dim jConfig As New JSONCollection
  30.   Dim obj As Object = Me
  31.   Dim MyClass As Class = Object.Class(obj)
  32.   Dim Var As String
  33.   Dim Valor As Variant
  34.   If sFile = "" Then
  35.     sFile = User.Home &/ ConfigFile
  36.   For Each Var In myClass.Symbols
  37.     '' Verifying that it is a property or a variable.
  38.     If (MyClass[var].kind = Class.Variable) Or (MyClass[var].kind = Class.Property) Then
  39.       valor = Object.GetProperty(obj, var)
  40.       jConfig.Add(Valor, var)
  41.     End If
  42.   Next
  43.   If Not Exist(File.Dir(sFile)) Then
  44.     Shell "mkdir -p " & File.Dir(sFile) Wait
  45.   File.Save(sFile, JSON.Encode(jConfig))
  46.  

For example in a form…

Code (gambas)

  1. Public Sub Form_Open()
  2.   Config.Load()
  3.   Print "Color saved", Config.CurrentColor
  4.   Config.CurrentColor = Rand(0, 255)
  5.   Print "Color to save", Config.CurrentColor
  6.   Config.Save()
  7.  

Regards.
Martín.

Attachment
Online now: No Back to the top
1 guest and 0 members have just viewed this.