Config class + Json file

So you have written that new, must have program. Let us see it here.
Post Reply
User avatar
tincho
Posts: 41
Joined: Wednesday 10th July 2019 1:12pm

Config class + Json file

Post by tincho » Tuesday 01st June 2021 8:27am

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
' Gambas class file
Create Static
Export
Private Const ConfigFile As String = ".app/config.json"
''Configuration variables to be saved, add as needed below
Public CurrentColor As Byte = 1
Public CurrentWidth As Byte = 1
Public CurrentLType As Byte = 1
Public OtherParameter1 As String = "gambas-es.org"
Public OtherParameter2 As String = "gambas.one"
Public OtherParameter3 As String = "gambas-club.de"
Public OtherParameter4 As String = "gambas-it.org"

Public Sub Load(Optional sFile As String)

  Dim jConfig As Collection
  Dim i As Integer
  Dim sSymbol As String
  Dim obj As Object = Me
  Dim MyClass As Class = Object.Class(obj)

  If sFile = "" Then
    sFile = User.Home &/ ConfigFile
  Endif

  If Exist(sFile) Then
    jConfig = JSON.FromString(File.Load(sFile))
    For Each sSymbol In myClass.Symbols
      If jConfig.Exist(sSymbol) Then
        Object.SetProperty(obj, sSymbol, jConfig[sSymbol])
      Endif
    Next
  Endif
End

Static Public Sub Save(Optional sFile As String)
  Dim i As Integer
  Dim jConfig As New JSONCollection
  Dim obj As Object = Me
  Dim MyClass As Class = Object.Class(obj)
  Dim Var As String
  Dim Valor As Variant
  If sFile = "" Then
    sFile = User.Home &/ ConfigFile
  Endif
  For Each Var In myClass.Symbols
    '' Verifying that it is a property or a variable.
    If (MyClass[var].kind = Class.Variable) Or (MyClass[var].kind = Class.Property) Then
      valor = Object.GetProperty(obj, var)
      jConfig.Add(Valor, var)
    End If
  Next
  If Not Exist(File.Dir(sFile)) Then
    Shell "mkdir -p " & File.Dir(sFile) Wait
  Endif
  File.Save(sFile, JSON.Encode(jConfig))
End
For example in a form...
Public Sub Form_Open()
  Config.Load()
  Print "Color saved", Config.CurrentColor
  Config.CurrentColor = Rand(0, 255)
  Print "Color to save", Config.CurrentColor
  Config.Save()
End
Regards.
Martín.
Attachments
Configurator-0.0.4.tar.gz
(38.6 KiB) Downloaded 68 times

Post Reply