Skip to content

Instantly share code, notes, and snippets.

@pselden
Created January 13, 2015 20:54
Show Gist options
  • Save pselden/093965d29fc95ec7026b to your computer and use it in GitHub Desktop.
Save pselden/093965d29fc95ec7026b to your computer and use it in GitHub Desktop.
'use strict';
var fs = require('fs');
var gulp = require('gulp');
var extend = require('gulp-multi-extend');
var merge = require('merge-stream');
var path = require('path');
var connect = require('gulp-connect');
var localesDir = './app/resources/locales/';
var localesGlob = localesDir + '*.json';
/**
* Loops through contents of the locales directory and returns the 'base' languages (those with only a language and not a locale.
* @returns {String[]} An array of base languages found in the locales directory. EX: ['en', 'fr']
*/
function getBaseLangs(){
return fs.readdirSync(localesDir)
.filter(function(locale){
return locale.split('-').length === 1;
}).map(function(locale){
return path.basename(locale, '.json');
});
}
/**
* Merges locale data files to create "fallbacks" from locales to languages as build time.
* The following fallback is used.
* 1. The contents of the full locale EX: 'fr-FR.json'
* 2. The contents of the language EX: 'fr.json'
* 3. The contents of 'en.json'
* @returns {*} A gulp stream.
*/
function translations() {
var merged = merge();
getBaseLangs().forEach(function(lang){
var baseLang = [localesDir, lang, '.json'].join('');
var globs = [
[localesDir, lang, '-*.json'].join(''),
baseLang
];
var stream = gulp.src(globs, {base: './app/'})
.pipe(extend(baseLang))
.pipe(extend(localesDir + 'en.json'))
.pipe(gulp.dest('dist'));
merged.add(stream);
});
return merged.pipe(connect.reload());
}
function watch(tasks){
return function(){
return gulp.watch(localesGlob, tasks);
};
}
exports.translations = translations;
exports.watch = watch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment