Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/twbs/rewire.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohannes <mail@johannesewald.de>2012-06-12 01:29:10 +0400
committerJohannes <mail@johannesewald.de>2012-06-12 01:29:10 +0400
commit0af1dcb6b2ccbc7ec0ae757549688e666cf569a7 (patch)
tree4b3854b937ff1f05bf8677c8fc1547fa733e6feb /lib/__set__.js
parent75f6a7765a09344dab54a4a2ca99ac12f547a75d (diff)
- changed APIv0.2.0
- introduced __set__ and __get__ to rewired modules
Diffstat (limited to 'lib/__set__.js')
-rw-r--r--lib/__set__.js41
1 files changed, 41 insertions, 0 deletions
diff --git a/lib/__set__.js b/lib/__set__.js
new file mode 100644
index 0000000..7de8eec
--- /dev/null
+++ b/lib/__set__.js
@@ -0,0 +1,41 @@
+"use strict"; // run code in ES5 strict mode
+
+/**
+ * This function will be stringified and then injected into every rewired module.
+ * Then you can set private variables by calling myModule.__set__("myPrivateVar", newValue);
+ *
+ * @param {!String|!Object} varName name of the variable to set
+ * @param {String} varValue new value
+ * @throws {TypeError}
+ * @return {*}
+ */
+module.exports = function __set__(varName, varValue) {
+ var key,
+ env,
+ src = "";
+
+ function checkExistsSrc(varName) {
+ return "if (typeof " + varName + " === 'undefined') { throw new ReferenceError('" + varName + " is not defined');} ";
+ }
+
+ if (typeof varName === "object") {
+ env = varName;
+ if (!env || Array.isArray(env)) {
+ throw new TypeError("__set__ expects an object as env");
+ }
+ for (key in env) {
+ if (env.hasOwnProperty(key)) {
+ src += checkExistsSrc(key) + key + " = env." + key + ";";
+ }
+ }
+ } else if (typeof varName === "string") {
+ if (!varName) {
+ throw new TypeError("__set__ expects a non-empty string as a variable name");
+ }
+ src = checkExistsSrc(varName) + varName + " = varValue;"
+ } else {
+ throw new TypeError("__set__ expects an environment object or a non-empty string as a variable name");
+ }
+
+ eval(src);
+}; \ No newline at end of file