Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

localez

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

localez

Localize from single string for genders, numbers, and number to text.

  • 0.0.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2
Maintainers
1
Weekly downloads
 
Created
Source

Localez

****>> STILL UNDER CONSTRUCTION <<****

Localization is a pain, specially when dealing with gender specific translations, other libraries have tackled this with complex json/xml structures. This library avoids this by working similar to existing templating libraries, allowing translation to be self contained and inline with text.

The translation file is automatically loaded using navigator user-agent or require statement. This file contains the each translation string, stored by a unique number. Below is a gulp task that will generate the file automatically looking for references of locale invokers __('') or {{__ ""}}.

May make the unique number optional and let developer decide to use STRINT CONST instead.

Example

/** fr.js (loaded locale) **/
locale = {
  '-4213': 'Bonjour'
}

/** From code **/
__('Morning')
// Bonjour

/** You can pass gender alternatives and pluralizers **/
__('If {{g donator male(he) female(she) }} only had given {{g receiver male(him) female(her) }} {{i data.flowers zero( flowers) one( flower) other( flowers)}} then they\'d lived happily ever after.', {donator: 'male', receiver: 'female', data : { flowers: 1 }})
// If he only had given her 1 flower then they'd lived happily ever after.


Specification

Parse a string and inject appropriate variables if required.

__(STRING, [OBJECT])

The library works by first retrieving exact match of string from the stored locale (which is loaded on launch), it then parses that string for Types which has Options

Types
Type LongType ShorthandType Options
gendergCan be what ever you want, it just needs to match up to variable passed in: male or female
integerizero, one, few, many, other
numbernzero, one, few, many, other

In any type the second argument is the variable used for options, the variable is gained from the passed in object.

Anything inside an option is also parsed for locale expressions

Examples
Genders
__('It\'s a {{g profile male(Mans) female(Womens)}} world.', {profile: 'male'})
// It's a Mans world.
Integers (pluralization)
__('There\'s {{i bottles other( bottles) one( bottle)}} of beer on the wall.', {flowers: 99})
// There's 99 bottles of beer on the wall.

n.b. The library lets you decide if you want a gap between numbers or not.

Numbers (pluralization)
__('There\'s {{n bottles other( bottles) one( bottle)}} of beer on the wall.', {flowers: 99})
// There's ninety nine bottles of beer on the wall.
Config per locale

Inside the locale that's loaded you can add a config that will changed how the string is parsed.

config: {
  debug: false,
}
OptionDefault
debugIf debug is enabled or not, default is false
debugConsoleStyle
    warnbackground: #990f0f; color: #ffc7c7Styling for warning messages in console
    errorbackground: #990f0f; color: #ffc7c7tyling for error messages in console
openTag{{string to match on for opening an expression
closeTag}}string to match on for closing an expression
matchers
    type/^(\s+)?\w+/iRegex to extract the type inside an expression
    variable/^(\s+)?[\w.]+/iRegex to extract the variable in an expression
markersThese are the markers for types
    gender['gender', 'g']Determins if the expression is a gender type
    integer['integer', 'i']Determins if the expression is a integer type
    number['number', 'n']Determins if the expression is a number type
numberEnumNot sure these should be exposed ....
    zerozero
    oneone
    twotwo
    fewfew
    manymany
    otherother
numbersfunction(number, enums)A function to decide which enum the value of the variable is, used to pick the option inside an expression
numberToStringfunction(number, enums)A function to convert an integer into number text (1 -> one)

Locale Generation

Below is a gulp task that will crawl your source directory for any translation references and spit them out to ./locales/output.js

var gulp = require('gulp'),
    file = require('file');

gulp.task('localez-parser', function() {

	var dest = './locales/output.js',
		prefix = 'locale = ',
		filesCount  = 0,
		filesParsed = 0,
		results     = {},
		ext         = /\.(js(|x)|hbs|jade|es6)$/,
		patterns    = [
			"__\\('(.*?)'\\)",
			"\\{\\{__\\s'(.*?)'\\}\\}",
			'__\\("(.*?)"\\)',
			'\\{\\{__\\s"(.*?)"\\}\\}'
		];

	String.prototype.hashCode = function() {
		var hash = 0, i, chr, len;
		if (this.length == 0) return hash;
		for (i = 0, len = this.length; i < len; i++) {
			chr   = this.charCodeAt(i);
			hash  = ((hash << 5) - hash) + chr;
			hash |= 0; // Convert to 32bit integer
		}
		return hash;
	};

	function parse(file) {

		patterns.forEach(function(pattern, i) {

			var regexGlobal = new RegExp(pattern, 'gmi'),
				regexFilter = new RegExp(pattern, 'mi'),
				keys = file.match(regexGlobal);

			if(!keys) return;

			keys.forEach(function(string) {

				var key = string.match(regexFilter)[1];

				if(key) results[key.hashCode()] = key;

			});

		});

	}

	file.walk('./js/', function(err, dir, dirs, files) {

		if(err) throw err;

		files.forEach(function(file) {

			if(file.match(ext) && !file.match('.min.')) {

				filesCount ++;

				fs.readFile(file, 'utf8', function(err, file) {

					if(err) throw err;

					parse(file);

					filesParsed++;

					if(filesParsed >= filesCount) save();

				})

			}

		});

	});

	function sortObject(map) {
		var newObject = {},
			keys =_.sortBy(_.keys(map), function(a) { return map[a] });
		_.each(keys, function(k) {
			newObject[k] = map[k];
		});
		return newObject;
	}

	function save() {

		var data = JSON.stringify(sortObject(results), null, 4);

		console.log('\nSuccessfully parsed a locale to', dest, '\n\n', data);

		fs.writeFile(dest, prefix + data, 'utf-8', function (err) {
			if (err) return console.log(err);
		});

	}

});

Keywords

FAQs

Package last updated on 22 Oct 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc