Skip to content

Commit dea8d79

Browse files
efahlsystemcrash
authored andcommitted
luci-base: add uci.get_bool to allow cleanup of app code
Any number of apps read boolean values from configuration files, then use various inconsistent means for checking truth values. The get_bool function allows app authors to fetch the value without regard for how it is represented in the config file. For example, this let enabled = uci.get('system', 'ntp', 'enable_server'); if (enabled == '1') ... could become the more natural let enabled = uci.get_bool('system', 'ntp', 'enable_server'); if (enabled) ... Signed-off-by: Eric Fahlgren <ericfahlgren@gmail.com>
1 parent 8b00d02 commit dea8d79

File tree

1 file changed

+34
-0
lines changed
  • modules/luci-base/htdocs/luci-static/resources

1 file changed

+34
-0
lines changed

modules/luci-base/htdocs/luci-static/resources/uci.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,40 @@ return baseclass.extend(/** @lends LuCI.uci.prototype */ {
704704
return this.get(conf, sid, opt);
705705
},
706706

707+
/**
708+
* A special case of `get` that always returns either `true` or
709+
* `false`.
710+
*
711+
* Many configuration files contain boolean settings, such as
712+
* `enabled` or `advanced_mode`, where there is no consistent
713+
* definition for the values. This function allows users to
714+
* enter any of the values `"yes"`, `"on"`, `"true"` or `1` in
715+
* their config files and we return the expected boolean result.
716+
*
717+
* Character case is not significant, so for example, any of
718+
* "YES", "Yes" or "yes" will be interpreted as a `true` value.
719+
*
720+
* @param {string} conf
721+
* The name of the configuration to read.
722+
*
723+
* @param {string} sid
724+
* The name or ID of the section to read.
725+
*
726+
* @param {string} [opt]
727+
* The option name from which to read the value. If the option
728+
* name is omitted or `null`, the value `false` is returned.
729+
*
730+
* @returns {boolean}
731+
* - Returns boolean `true` if the configuration value is defined
732+
* and looks like a true value, otherwise returns `false`.
733+
*/
734+
get_bool(conf, type, opt) {
735+
let value = this.get(conf, type, opt);
736+
if (typeof(value) == 'string')
737+
return ['1', 'on', 'true', 'yes', 'enabled'].includes(value.toLowerCase());
738+
return false;
739+
},
740+
707741
/**
708742
* Sets the value of the given option within the first found section
709743
* of the given configuration matching the specified type or within

0 commit comments

Comments
 (0)