1+ 'use strict' ;
2+
3+ var fs = require ( 'fs' ) ;
4+ var path = require ( 'path' ) ;
5+ var po2json = require ( 'po2json' ) ;
6+ var Jed = require ( 'jed' ) ;
7+ var translators = { } ;
8+ var poData = { } ;
9+
10+ function I18NHelper ( options ) {
11+ this . poFilePath = options . poFilePath ;
12+ this . poFileName = options . poFileName || 'messages.po' ;
13+ this . domain = options . domain ;
14+ this . defaultLocale = options . defaultLocale || 'en_US' ;
15+ }
16+
17+ I18NHelper . prototype = {
18+ loadLocaleData : function ( locale ) {
19+ if ( ! translators [ locale ] && ! poData [ locale ] ) {
20+ if ( ! fs . existsSync ( path . join ( this . poFilePath , locale , this . poFileName ) ) ) {
21+ locale = this . defaultLocale ;
22+ }
23+ poData [ locale ] = po2json . parseFileSync ( path . join ( this . poFilePath , locale , this . poFileName ) , {
24+ format : 'jed1.x' ,
25+ domain : this . domain
26+ } ) ;
27+ translators [ locale ] = new Jed ( poData [ locale ] ) ;
28+ }
29+ } ,
30+
31+ getTranslator : function ( locale ) {
32+ this . loadLocaleData ( locale ) ;
33+ return translators [ locale ] ;
34+ } ,
35+
36+ getPoData : function ( locale ) {
37+ this . loadLocaleData ( locale ) ;
38+ return poData [ locale ] ;
39+ } ,
40+
41+ getClosestTranslation : function ( locale , key ) {
42+ var translation = null ;
43+ if ( this . translationExists ( locale , key ) ) {
44+ translation = this . getTranslator ( locale ) . translate ( key ) ;
45+ } else if ( this . defaultTranslationExists ( key ) ) {
46+ translation = this . getDefaultTranslation ( key ) ;
47+ }
48+ return translation ;
49+ } ,
50+
51+ getDefaultTranslation : function ( key ) {
52+ return this . getTranslator ( this . defaultLocale ) . translate ( key ) ;
53+ } ,
54+
55+ translationExists : function ( locale , key ) {
56+ return ! ! ( this . getPoData ( locale ) && this . getPoData ( locale ) . locale_data [ this . domain ] && this . getPoData ( locale ) . locale_data [ this . domain ] [ key ] ) ;
57+ } ,
58+
59+ defaultTranslationExists : function ( key ) {
60+ return ! ! this . getPoData ( this . defaultLocale ) . locale_data [ this . domain ] [ key ] ;
61+ }
62+ } ;
63+
64+ module . exports = I18NHelper ;
0 commit comments