Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add i18n.t method to look up translations

  • Loading branch information...
commit ef278f16f2c12a5ebee3109c77e6d9cc648661bb 1 parent 2f2c46b
@jeremyruppel authored
Showing with 49 additions and 2 deletions.
  1. +14 −1 bin/walrus.js
  2. +11 −1 lib/walrus/i18n.coffee
  3. +24 −0 test/i18n_spec.coffee
View
15 bin/walrus.js
@@ -496,7 +496,20 @@ if (typeof module !== 'undefined' && require.main === module) {
}
;
- Walrus.i18n = {};
+ Walrus.i18n = {
+ t: function(keypath, context) {
+ var string;
+ if (context == null) context = {};
+ try {
+ string = Walrus.Utils.keypath(keypath, this[this.locale]);
+ return Walrus.Utils.interpolate(string, context);
+ } catch (error) {
+ throw new Error("Missing translation: " + this.locale + "." + keypath);
+ }
+ },
+ locale: 'en',
+ en: {}
+ };
Utils = {
/**
View
12 lib/walrus/i18n.coffee
@@ -1 +1,11 @@
-Walrus.i18n = { }
+Walrus.i18n = {
+ t : ( keypath, context={} ) ->
+ try
+ string = Walrus.Utils.keypath keypath, @[ @locale ]
+ Walrus.Utils.interpolate string, context
+ catch error
+ throw new Error "Missing translation: #{@locale}.#{keypath}"
+
+ locale : 'en' # default for now
+ en : { }
+}
View
24 test/i18n_spec.coffee
@@ -0,0 +1,24 @@
+require '../bin/walrus'
+
+should = require 'should'
+
+describe 'Walrus.i18n', ->
+
+ describe 'locale', ->
+ it 'should be defined', -> should.exist Walrus.i18n.locale
+
+ describe 't', ->
+
+ before -> Walrus.i18n.locale = 'en'
+ before -> Walrus.i18n.en.whatever = { greeting : 'Sup %{name}!' }
+
+ it 'should look up the proper value in the locale', ->
+ Walrus.i18n.t( 'whatever.greeting' ).should.equal( 'Sup %{name}!' )
+
+ it 'should interpolate the context into the string if given', ->
+ Walrus.i18n.t( 'whatever.greeting', name : 'broseph' ).should.equal( 'Sup broseph!' )
+
+ it 'should throw an error on a missing keypath', ->
+ ( ->
+ Walrus.i18n.t 'whatever.nothings.here'
+ ).should.throw( 'Missing translation: en.whatever.nothings.here' )
Please sign in to comment.
Something went wrong with that request. Please try again.