Bug 1294186 - Add memoized getter for properties files in l10n.js;r=bgrins
authorJulian Descottes <jdescottes@mozilla.com>
Thu, 25 Aug 2016 11:22:37 +0200
changeset 408582 8afcd614f50e3e0301a10a5dc890484a68b94af6
parent 408581 9d715b38e5f094c63df4fa560fd00b6ff6852f9b
child 408583 cba87d584348ee62004f8d7893529c9b37a6bded
push id28254
push userjdescottes@mozilla.com
push dateThu, 01 Sep 2016 10:25:22 +0000
reviewersbgrins
bugs1294186
milestone51.0a1
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
devtools/shared/l10n.js
--- 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.
    *