-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
42 lines (41 loc) · 1.32 KB
/
index.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
var slugify = require('./deps/slug.js');
module.exports = function(attrs, fmt) {
return function(Model) {
Model.attr('slug');
if(typeof attrs == 'string') {
Model.on('initialize', function(model) {
if(!model.slug) model.slug = slugify(model[attrs]);
});
Model.on('change ' + attrs, function(model) {
model.slug = slugify(model[attrs]);
});
} else if(typeof fmt == 'string') {
Model.on('initialize', function(model) {
if(!model.slug) model.slug = formatString(model);
});
attrs.forEach(function(attr) {
Model.on('change ' + attr, function(model) {
model.slug = formatString(model);
});
});
} else {
Model.on('initialize', function(model) {
if(!model.slug) model.slug = slugify(fmt(model));
});
attrs.forEach(function(attr) {
Model.on('change ' + attr, function(model) {
model.slug = slugify(fmt(model));
});
});
}
};
function formatString(model) {
var result = fmt;
var replace = fmt.match(/:\w+/g);
replace.forEach(function(attr) {
var regex = new RegExp(attr, 'g');
result = result.replace(regex, model[attr.slice(1)]);
});
return slugify(result);
}
};