Skip to content

Instantly share code, notes, and snippets.

@solomonhawk
Last active August 29, 2015 14:21
Show Gist options
  • Save solomonhawk/80c0a3ae065a7531d4dd to your computer and use it in GitHub Desktop.
Save solomonhawk/80c0a3ae065a7531d4dd to your computer and use it in GitHub Desktop.
/**
* Somewhere in an app module, pull in the app specific translator
*/
import t from 'util/translate'
t("Edu_bs")
// => "Bachelor's"
/**
* Somewhere in your app code, pull in the translator factory
* along with app specific translations and create a
* translator specific to our app
*/
import createTranslator from 'lib/translate'
import defaults from 'app/config/translations'
export default createTranslator(defaults)
/**
* App specific translations
*/
export default {
"Income_U_50" : "Under $50k",
"Income_50_100" : "$50 - 100k",
"Income_100_O" : "Over $100k",
"Edu_bs" : "Bachelor's",
"Edu_ms" : "Master's",
"Never_married" : "Never Married",
"Married_other" : "Married - Other",
"Married" : "Married",
"Parent" : "Parent",
"Homeowner" : "Homeowner",
"Renter" : "Renter",
"Hh_U_150" : "Under 150k",
"Hh_150_250" : "150 - 250k",
"Hh_250_500" : "250 - 500k",
"Hh_500_750" : "500 - 750k",
"Hh_750_O" : "Over 750k",
"Car_alone" : "Car - Alone",
"Car_carpool" : "Carpool",
"Public_transportation" : "Public",
"Commute_U_20": "Under 20 Min",
"Commute_20_39": "20 - 39 Min",
"Commute_40_O": "Over 40 Min"
}
/**
* Test fixture for testing the translator factory in isolation
* from the app specific translations
*/
export default {
"foo": "bar"
}
/**
* Exports a function that takes a translations object and returns
* a function that can be used to translate strings in the provided
* dictionary
*/
export default (translations) => {
return function translate(input) {
if (translations.hasOwnProperty(input) === false) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`Unknown string "${ input }" for translation.`)
}
return input
}
return translations[input]
}
}
/**
* A test for the translator (isolated from app specific code) that ensures
* it translates strings within the provided translations and also that
* it provides a console warning if the provided string isn't found
*/
import createTranslator from '../index'
import config from 'test/fixtures/translate'
let t = createTranslator(config)
describe('translations', function() {
it('returns a translated string', function() {
let result = t('foo')
expect(result).to.equal('bar')
})
describe('when given an unknown string', function() {
let message = 'Unknown string "not found" for translation.'
let spy = sinon.spy()
let stub = sinon.stub(console, 'warn', spy)
it('returns the original string and warns the developer', function() {
let result = t('not found')
expect(spy.calledWith(message))
expect(result).to.equal('not found')
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment