-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathSubstitution.js
79 lines (66 loc) · 1.67 KB
/
Substitution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
define( [ "ember" ], function( Ember ) {
var get = Ember.get;
var reSubstitution = /\{([a-z]+)}/ig;
var reEscape = /(["'`$\\])/g;
var strEscape = "\\$1";
var reWhitespace = /\s+/g;
/**
* @class Substitution
* @param {(string|string[])} vars
* @param {string} path
* @param {string?} description
* @constructor
*/
function Substitution( vars, path, description ) {
this.vars = Ember.makeArray( vars );
this.path = path;
this.description = description;
}
/**
* @param {string} name
* @returns {boolean}
*/
Substitution.prototype.hasVar = function( name ) {
return this.vars.indexOf( name ) !== -1;
};
/**
* @param {Object} obj
* @returns {(string|boolean)}
*/
Substitution.prototype.getValue = function( obj ) {
var val = get( obj, this.path );
if ( val === undefined ) {
return false;
}
return String( val )
// escape special characters
.replace( reEscape, strEscape )
// remove whitespace
.replace( reWhitespace, " " )
.trim();
};
/**
* Apply multiple substituions at once.
* @param {string} str
* @param {(Substitution|Substitution[])} substitutions
* @param {Object} obj
*/
Substitution.substitute = function( str, substitutions, obj ) {
substitutions = Ember.makeArray( substitutions );
return str.replace( reSubstitution, function( all, name ) {
name = name.toLowerCase();
var res = false;
// find the first matching variable and get its value
substitutions.some(function( substitution ) {
if ( substitution.hasVar( name ) ) {
res = substitution.getValue( obj );
return true;
}
});
return res === false
? all
: res;
});
};
return Substitution;
});