Bug 1294186 - Add memoized getter for properties files in l10n.js;r=bgrins
Localization properties files should not change during a session. To allow
callers to easily localize strings without having to instanciate LocalizationHelper
objects, we should cache the already required properties files.
This will for now only be used internally by the LocalizationHelper as well as
by the markup localization utility. But we could now use this to provide static
localization methods.
MozReview-Commit-ID: 85agGNJlIk9
--- a/devtools/shared/l10n.js
+++ b/devtools/shared/l10n.js
@@ -1,44 +1,55 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const parsePropertiesFile = require("devtools/shared/node-properties/node-properties");
const { sprintf } = require("devtools/shared/sprintfjs/sprintf");
+const propertiesMap = {};
+
+/**
+ * Memoized getter for properties files that ensures a given url is only required and
+ * parsed once.
+ *
+ * @param {String} url
+ * The URL of the properties file to parse.
+ * @return {Object} parsed properties mapped in an object.
+ */
+function getProperties(url) {
+ if (!propertiesMap[url]) {
+ propertiesMap[url] = parsePropertiesFile(require(`raw!${url}`));
+ }
+
+ return propertiesMap[url];
+}
+
/**
* Localization convenience methods.
*
* @param string stringBundleName
* The desired string bundle's name.
*/
function LocalizationHelper(stringBundleName) {
this.stringBundleName = stringBundleName;
}
LocalizationHelper.prototype = {
- get properties() {
- if (!this._properties) {
- this._properties = parsePropertiesFile(require(`raw!${this.stringBundleName}`));
- }
-
- return this._properties;
- },
-
/**
* L10N shortcut function.
*
* @param string name
* @return string
*/
getStr: function (name) {
- if (name in this.properties) {
- return this.properties[name];
+ let properties = getProperties(this.stringBundleName);
+ if (name in properties) {
+ return properties[name];
}
throw new Error("No localization found for [" + name + "]");
},
/**
* L10N shortcut function.
*