tincho   01-06-2021, 10:37
#1
[Imagen: nnwUBmA.jpg]
Hola amigos.
Deseo presentarles un método para gestionar la configuración de  un programa, que a mi me parece interesante.
En conjunto con TercoIDE preparamos este ejemplo en el cual en una clase existen todos los parámetros de un programa y con gran flexibilidad pueden agregarse mas. Luego en cualquier otra parte del programa se pueden leer y escribir esas variables.
Finalmente existe un método (Save) que recorre los simbolos de la clase y los guarda en un archivo de texto en formato json para futuros usos recuperando estos datos con el método "Load".
Por favor siéntanse en libertad de opinar, comentar o mejorar este programa.
Config.class
Código:
' 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

Por ejemplo en un formulario...
Código:
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

Agregado  - 2021.08.20
Este método extiende la clase JSON y lo que hace es codificar el texto Json en una forma mas legible para humanos. Para usarla tienen que crear una clase en su proyecto que se llame JSON (con mayúsculas) y luego poner este código (Encode2) listo luego en vez de usar JSON.Encode en sus proyectos usen JSON.Encode2 y listo.
Código:
' Gambas class file

'
' Copyright (C) GauchoCAD Team
'
' This program is free software; you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation; either version 2 of the License, or
' (at your option) any later version.

Export

'' Encode in JSON format in a human readable way. Based on a Laurent tool

Static Public Function Encode2(vData As Variant) As String
 
  Dim sInput As String
  Dim sOutput As String
  Dim iStream As Stream
 
  Dim $sReadChar As String
  Dim $iTab As Integer
  Dim $bQuote, $bBracket As Boolean
 
  sInput = JSON.Encode(vData)
 
  iStream = Open String sInput For Read
 
  While (Not Eof(iStream))
    $sReadChar = Read #iStream, 1
    If ($sReadChar = "{" And Not $bQuote) Then
      $iTab += 1
      $sReadChar &= "\n" & Space$($iTab * 2)
    Else If ($sReadChar = "}" And Not $bQuote) Then
      $iTab -= 1
      $sReadChar = "\n" & Space$($iTab * 2) & $sReadChar
    Else If ($sReadChar = "\"") Then
      $bQuote = Not $bQuote
    Else If ($sReadChar = "[") Then
      $bBracket = True
    Else If ($sReadChar = "]") Then
      $bBracket = False
    Else If ($sReadChar = ":" And Not $bQuote) Then
      $sReadChar &= " "
    Else If ($sReadChar = "," And Not $bQuote) Then
      If (Not $bBracket) Then
        $sReadChar &= "\n" & Space$($iTab * 2)
      Else
        $sReadChar &= " "
      Endif
    Endif
    sOutput &= $sReadChar
  Wend
 
  Close iStream
  ' replace null with ""
  sOutput = Replace(sOutput, " null", " \"\"")
 
  Return sOutput
 
End

Agregado  - 2023.05.04 - Proyecto de estudio que utiliza la clase Config. Hay un nuevo control, una clase llamada ListMaker, que permite la edición de lista de datos.

Saludos.
Archivos adjuntos
.gz
json-config-0.0.3.tar.gz (Tamaño: 44.64 KB Descargas: 5)
Última modificación: 05-05-2023, 00:32 por tincho.

1 Saludo.
  
Usuarios navegando en este tema: 1 invitado(s)
Powered By MyBB, © 2002-2025 MyBB Group.
Made with by Curves UI.