PolymerElements / app-localize-behavior

Polymer behaviour to help internationalize your application
48 stars 54 forks source link

add optional preprocessor param to loadResources #110

Closed jab closed 7 years ago

jab commented 7 years ago

Hey again,

We had another core localization need that other users might share, so here goes another PR, in case it's helpful!

This change adds an optional second parameter to loadResources, a preprocessor function, which if supplied, will be called on the loaded data before assigning it to resources.

I think this fixes #75 and #103.

Background

My team will be using Transifex for managing our translations. (If you're working on an Internet freedom project and trying to make it accessible to as many users as possible, Transifex is the place to be.)

Transifex expects you to keep your resources for each language in a separate file of flat messages, so like:

./locales/
  ├── en.json    // {"hi": "hi"}
  └── es.json    // {"hi": "hola"}

In contrast, AppLocalizeBehavior expects you to store resources for a given language nested inside the key for that language, e.g. {"es": {"hi": "hola"}}.

Since our translation platform doesn't support that format, we currently resort to calling loadResources to fetch our flattened resources for the currently-needed language, resulting in resources temporarily getting set to data in the wrong format. Then we have an observer that notices when resources has changed, checks if the data is in the flattened/wrong format, and if so, sets resources to the expected format. Which is unfortunately convoluted and less efficient.

Being able to pass an optional preprocessor function to loadResources would allow us to get the fetched data into the right format from the get-go:

attached: function() {
  this.loadResources(

    // Only contains the flattened "es" translations:
    'locales/es.json',  // {"hi": "hola"}

    function preprocess(resources) {
      return {es: resources};  // unflatten -> {"es": {"hi": "hola"}}
    }
  );
}

It also adds a bit more flexibility to support other formats, as long as a preprocessor function can be supplied that returns the data in the format that AppLocalizeBehavior is expecting.

If there is interest in adding support for this, and this PR is on the right track, I'm happy to put any further work into it to get it into a mergeable state!

Thanks for your consideration, and thanks again for the great work on Polymer!

jab commented 7 years ago

Closing in preference to #111.