Gambas France BETA


Pas de compte ? Incription

Config

À propos de ce code

Un exemple d'utilisation de la classe config pour gérer la configuration d'un programme. Il vous permet de stocker et de récupérer des valeurs variables de manière propre, simple et ordonnée.
Il permet d'ajouter facilement des variables à la volée tout en écrivant du code, car tout est ajouté en un seul endroit.
Il vous permet ensuite d'utiliser l'opérateur point pour récupérer la liste des variables.

Code source

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
' Gambas class file

CREATE STATIC
EXPORT
PUBLIC AppDir AS STRING
PUBLIC Depot AS STRING
''Configuration variables to be saved, add as needed below
PUBLIC iByte AS BYTE
PUBLIC iShort AS SHORT
PUBLIC iInteger AS INTEGER
PUBLIC iLong AS LONG
'Public fSingle As Single
PUBLIC fFloat AS FLOAT
PUBLIC sString AS STRING = "Tincho"

PUBLIC SUB Load(sFile AS STRING)

DIM cConfig AS Collection
DIM sSymbol AS STRING
DIM obj AS OBJECT = ME
DIM MyClass AS Class = Object.Class(obj)

IF Exist(sFile) THEN
cConfig = JSON.FromString(File.Load(sFile))
FOR EACH sSymbol IN myClass.Symbols
IF cConfig.Exist(sSymbol) THEN
Object.SetProperty(obj, sSymbol, cConfig[sSymbol])
ENDIF
NEXT
ENDIF

END

'' Update the Config variable
STATIC PUBLIC SUB Update(sTag AS STRING, vSet AS VARIANT)

DIM sSymbol AS STRING
DIM obj AS OBJECT = ME
DIM MyClass AS Class = Object.Class(obj)

FOR EACH sSymbol IN myClass.Symbols
IF sSymbol = sTag THEN
Object.SetProperty(obj, sSymbol, vSet)
BREAK
ENDIF
NEXT

END

STATIC PUBLIC SUB Save(sFile AS STRING)

DIM cConfig AS NEW Collection
DIM obj AS OBJECT = ME
DIM MyClass AS Class = Object.Class(obj)
DIM Var AS STRING
DIM Valor AS VARIANT

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)
cConfig.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.Encode2(cConfig))

END

Commentaires

Commentaire de tincho, Le 1/3/2022 à 12:33:43