Added the ability to add metadata to collections

This commit is contained in:
Anthony Short 2014-07-29 15:45:15 -07:00
parent 070cf3d75d
commit fd451bf4d9
5 changed files with 77 additions and 1 deletions

View file

@ -3,6 +3,8 @@ var debug = require('debug')('metalsmith-collections');
var extend = require('extend');
var Matcher = require('minimatch').Minimatch;
var unique = require('uniq');
var read = require('fs').readFileSync;
var yaml = require('yaml-js');
/**
* Expose `plugin`.
@ -90,6 +92,26 @@ function plugin(opts){
});
});
/**
* Add collection metadata
*/
keys.forEach(function(key){
debug('adding metadata: %s', key);
var settings = opts[key];
var col = metadata[key];
var fileName = settings.metadata;
if (!fileName) return;
if (typeof fileName === 'string') {
var data = read(fileName, 'utf-8');
var ext = fileName.substr(fileName.lastIndexOf('.') + 1);
col.metadata = ext === 'json' ? JSON.parse(data) : yaml.load(data);
}
else {
col.metadata = settings.metadata;
}
});
/**
* Add them grouped together to the global metadata.
*/

View file

@ -9,7 +9,8 @@
"debug": "~0.7.4",
"extend": "~1.2.1",
"minimatch": "^0.2.14",
"uniq": "0.0.2"
"uniq": "0.0.2",
"yaml-js": "0.0.7"
},
"devDependencies": {
"metalsmith": "0.x",

3
test/fixtures/metadata/metadata.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"name": "Batman"
}

1
test/fixtures/metadata/metadata.yaml vendored Normal file
View file

@ -0,0 +1 @@
name: Batman

View file

@ -145,4 +145,53 @@ describe('metalsmith-collections', function(){
done();
});
});
it('should add metadata objects to collections', function (done) {
var metalsmith = Metalsmith('test/fixtures/basic');
metalsmith
.use(collections({
articles: {
metadata: { name: 'Batman' }
}
}))
.build(function(err){
if (err) return done(err);
var m = metalsmith.metadata();
assert.equal('Batman', m.articles.metadata.name);
done();
});
});
it('should load collection metadata from a JSON file', function (done) {
var metalsmith = Metalsmith('test/fixtures/basic');
metalsmith
.use(collections({
articles: {
metadata: 'test/fixtures/metadata/metadata.json'
}
}))
.build(function(err){
if (err) return done(err);
var m = metalsmith.metadata();
assert.equal('Batman', m.articles.metadata.name);
done();
});
});
it('should load collection metadata from a YAML file', function (done) {
var metalsmith = Metalsmith('test/fixtures/basic');
metalsmith
.use(collections({
articles: {
metadata: 'test/fixtures/metadata/metadata.yaml'
}
}))
.build(function(err){
if (err) return done(err);
var m = metalsmith.metadata();
assert.equal('Batman', m.articles.metadata.name);
done();
});
});
});