Skip to content

Instantly share code, notes, and snippets.

@toadkicker
Last active April 15, 2019 07:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toadkicker/99551a94d0922e43a18aea7c6169a62e to your computer and use it in GitHub Desktop.
Save toadkicker/99551a94d0922e43a18aea7c6169a62e to your computer and use it in GitHub Desktop.
Convert Rails i18n YAML fies to JSON using Node. Built for vue-i18n to read json files from `config/locales/` in a Nuxt.js project.
module.exports = {
locales: [
{
code: 'en',
iso: 'en-US',
name: 'English',
file: 'en.json'
}
]
}
const yaml = require('js-yaml');
const fs = require('fs');
const localesConfig = require('./index');
// Read the Rails i18n en.yml file, write it to json in the locales directory.
// This is because we want a copy of the values to ship with the UI but only
// require the need to store them in one location. UI Components can still override
// these values when providing their own configuration.
module.exports = {
writeLocaleJsonFromRailsYaml: function (langCode = 'en') {
try {
let yml = yaml.safeLoad(fs.readFileSync(`../config/locales/${langCode}.yml`, 'utf8'));
fs.writeFileSync(`config/locales/${langCode}.json`, JSON.stringify(yml[langCode]), 'utf8', (err) => {
if (err) throw err;
console.log(`${langCode}.json has been saved to config/locales`);
});
} catch (e) {
console.log(e);
}
},
readLocaleJson: function (langCode) {
return JSON.parse(fs.readFileSync(`config/locales/${langCode}.json`, 'utf8'));
},
build: function () {
if (process.env.NODE_ENV === 'development') {
localesConfig.locales.forEach((locale) => {
this.writeLocaleJsonFromRailsYaml(locale.code);
})
}
}
}
@toadkicker
Copy link
Author

The intent of this was in a Nuxt.js app where we wanted to sync the Rails i18n YAML files into the UI at build time. This way the UI can ship with the locales separately from the back end rails app, while relieving us of putting locale data in two places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment