aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarak <[email protected]>2015-07-04 22:27:51 -0700
committerMarak <[email protected]>2015-07-04 22:27:51 -0700
commit24536095abdc41fb2741f6e6bfec7f6aea65ca22 (patch)
tree43efa959a2a8519c98d4ae4b8878b99b2f368408
parent658a0a55df28b7524481c9d49c7aa7c79432f3ea (diff)
downloadfaker-24536095abdc41fb2741f6e6bfec7f6aea65ca22.tar.xz
faker-24536095abdc41fb2741f6e6bfec7f6aea65ca22.zip
[api] First pass at generators with mustache strings. #226 #199 #171 #224
-rw-r--r--examples/generators.js13
-rw-r--r--lib/fake.js57
2 files changed, 70 insertions, 0 deletions
diff --git a/examples/generators.js b/examples/generators.js
new file mode 100644
index 00000000..78ce4d03
--- /dev/null
+++ b/examples/generators.js
@@ -0,0 +1,13 @@
+var faker = require('../index');
+
+faker.locale = "en";
+
+
+
+console.log(faker.fake('{{name.lastName}}, {{name.firstName}} {{name.suffix}}'));
+
+
+console.log(faker.fake('{{finance.currencyName}} - {{finance.amount}}'));
+
+
+console.log(faker.fake('{{name.firstName}} {{name.lastName}}')); \ No newline at end of file
diff --git a/lib/fake.js b/lib/fake.js
new file mode 100644
index 00000000..bad2ba9b
--- /dev/null
+++ b/lib/fake.js
@@ -0,0 +1,57 @@
+/*
+ fake.js - generator method for combining faker methods based on string input
+
+*/
+
+var faker = require('../');
+
+module['exports'] = function fake (str) {
+
+ // setup default response as empty string
+ var res = '';
+
+ // if incoming str parameter is not provided, return error message
+ if (typeof str !== 'string' || str.length === 0) {
+ res = 'string parameter is required!';
+ return res;
+ }
+
+ // find first matching {{ and }}
+ var start = str.search('{{');
+ var end = str.search('}}');
+
+ // if no {{ and }} is found, we are done
+ if (start === -1 && end === -1) {
+ return str;
+ }
+
+ // console.log('attempting to parse', str);
+
+ // extract method name from between the {{ }} that we found
+ // for example: {{name.firstName}}
+ var method = str.substr(start + 2, end - start - 2);
+ method = method.replace('}}', '');
+ method = method.replace('{{', '');
+
+ // console.log('method', method)
+
+ // split the method into module and function
+ var parts = method.split('.');
+
+ if (typeof faker[parts[0]] === "undefined") {
+ throw new Error('Invalid module: ' + parts[0]);
+ }
+
+ if (typeof faker[parts[0]][parts[1]] === "undefined") {
+ throw new Error('Invalid method: ' + parts[0] + "." + parts[1]);
+ }
+
+ // assign the function from the module.function namespace
+ var fn = faker[parts[0]][parts[1]];
+
+ // replace the found tag with the returned fake value
+ res = str.replace('{{' + method + '}}', fn());
+
+ // return the response recursively until we are done finding all tags
+ return fake(res);
+}; \ No newline at end of file