Effacer les filtres
Effacer les filtres

Set the properties of a class by reading values from initialization file

15 vues (au cours des 30 derniers jours)
Deepa Maheshvare
Deepa Maheshvare le 22 Août 2021
Modifié(e) : TADA le 24 Août 2021
This is a follow up to my previous question [here](https://in.mathworks.com/matlabcentral/answers/1437704-how-to-pass-a-class-to-matlab-executable).
I'm trying to set the properties of a class by loading the contents of the initialization file in a class method.
classdef setting
%SETTING Summary of this class goes here
% Detailed explanation goes here
properties(Constant)
n = setting.load_setting("n");
end
methods(Static)
function obj = load_setting(key)
ini = IniConfig();
ini.ReadFile('example.ini')
sections = ini.GetSections()
[keys, count_keys] = ini.GetKeys(sections{1})
values = ini.GetValues(sections{1}, keys)
% values = ini.GetValue(sections{1}, key)
end
end
end
example.ini includes the following
; example.ini -- INI file example for the class INiConfig
; UPD: 21.03.2010
; Supported whitespaces in section names
[Section 1] ; allowed the comment to section
n=10 ; numeric scalar
key12=1 ; numeric
key13=1 ; numeric
key14=Hello ; string
I could get all the keys and values present in a section of the initialization file via the GetKeys method (please see below) defined in IniConfig.
function [key_names, count_keys] = GetKeys(obj, section_name)
%GetKeys - get names of all keys from given section
%
% Using:
% key_names = GetKeys(section_name)
% [key_names, count_keys] = GetKeys(section_name)
%
% Input:
% section_name - name of section
%
% Output:
% key_names - cell array with the names of keys
% count_keys - number of keys in given section
% -------------------------------------------------------------
error(nargchk(2, 2, nargin));
section_name = obj.validateSectionName(section_name);
[key_names, count_keys] = obj.getKeys(section_name);
end
However, I am not sure how to get the value corresponding to a single key. For instance, I want to do
properties(Constant)
n = setting.load_setting("n"); % not sure if this is right; I want to fetch the value of key n from file.
end
%(commented in the method mentioned above; this method is not present
%in IniConfig class.
values = ini.GetValue(sections{1}, key)
I'd like to create a method for parsing the value of a key or zip keys and values obtained from the following. This would be similar to a dict in python but I am not sure how to do this in MATLAB. Suggestions wll be really helpful.
[keys, count_keys] = ini.GetKeys(sections{1})
values = ini.GetValues(sections{1}, keys

Réponse acceptée

dpb
dpb le 22 Août 2021
Why isn't it just the GetValues method?
function [values, status] = GetValues(obj, section_name, key_names, default_values)
%GetValues - get values of keys from given section
%
% Using:
% values = GetValues(section_name, key_names)
% values = GetValues(section_name, key_names, default_values)
%
% Input:
% section_name -- name of given section
% key_names -- names of given keys
% default_values -- values of keys that are returned by default
%
% Output:
% values -- cell array with the values of keys
% status -- 1 (true) - success, 0 (false) - failed
% -------------------------------------------------------------
...
from reading the source for the FEX submission. If that doesn't work, it would seem the place to ask would be the link given by the author since is not base MATLAB function.

Plus de réponses (1)

TADA
TADA le 24 Août 2021
Modifié(e) : TADA le 24 Août 2021
I would translate the file to JSON format and save the whole class instead of the key-value pairs of INI files
JSON is great for many reasons and you can get all the benefits of using a settings object (like property validators for one)
I would refrain from making this class static, as static classes are bad news for testing and scaling up your application.
I would load a single settings object on startup and pass it arround, but if you must, you can make a static instance of the class.
heres a simple example of a self saving/loading settings class, I made it a handle class so that you can make a single settings object, you can also edit that object at runtime and save your user preferences (such as the last browsed folder, etc.) and save the settings file when you close the app.
classdef SettingsClass < handle
% this settings class supports saving and loading from a json file
properties
X;
Y;
Z;
end
methods
function this = SettingsClass(A)
if nargin < 1; A = []; end
% generate from a struct of a settings class
if ~isempty(A) && (isstruct(A) || isa(A, 'SettingsClass'))
this.copyFromStruct(A);
% generate from a json file
elseif isStringScalar(A) || (ischar(A) && (isrow(A) || isscalar(A)))
load(this, A);
end
% otherwise, use default values
end
function copyFromStruct(this, s)
% copy all fields from supplied struct
% if the supplied struct has mismatched fields, an error will
% be thrown
fields = fieldnames(s);
for i = 1:numel(fields)
currField = fields{i};
this.(currField) = s.(currField);
end
end
function load(this, path)
% read the json file
json = fileread(path);
% decode the struct from json
s = jsondecode(json);
% copy struct into this object
this.copyFromStruct(s);
end
function save(this, path)
% encode this object into json format
json = jsonencode(this);
fid = [];
try
% write json config file
fid = fopen(path, 'w');
fwrite(fid, json);
catch ex
try
fclose(fid);
catch
% file was never properly opened... can't close it...
% just rethrow the original exception
end
ex.rethrow();
end
end
end
end

Produits


Version

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by