mongokit icon indicating copy to clipboard operation
mongokit copied to clipboard

set_lang is not really viable when retrieving data

Open ThiefMaster opened this issue 10 years ago • 2 comments

Usually there is some kind of global containing the current user's locale. Let's imagine a Flask application where I can get the current locale by calling get_locale().

Right now the only way to make use of this in MongoKit seems to be calling foo.set_lang(get_locale()) on every single object. This gets especially ugly when retrieving multiple objects and passing them to a template as a a list.

It would be much nicer if there was e.g. a default_lang setting which could be set to a callable that would be invoked whenever the current language needs to be retrieved.

ThiefMaster avatar Apr 13 '14 21:04 ThiefMaster

I'm now using this custom Document subclass to get the behaviour I was looking for:

from contextlib import contextmanager

from flask import current_app
from flask.ext.babel import get_locale
from flask.ext.mongokit import Document


class CustomDocument(Document):
    """Base MongoKit document with some useful features

    - Fallback language taken from app config
    - Active language taken from current locale
    - Context manager to temporarily change the language
    """

    def __init__(self, *args, **kwargs):
        self._current_lang_override = None
        super(CustomDocument, self).__init__(*args, **kwargs)
        self._current_lang = None
        self._fallback_lang = current_app.config['BABEL_DEFAULT_LOCALE']

    @property
    def _current_lang(self):
        if self._current_lang_override is not None:
            return self._current_lang_override
        return get_locale().language

    @_current_lang.setter
    def _current_lang(self, lang):
        self._current_lang_override = lang

    @contextmanager
    def change_lang(self, lang):
        """Temporarily changes the active language"""
        old_lang = self._current_lang_override
        self.set_lang(lang)
        yield
        self.set_lang(old_lang)

ThiefMaster avatar Apr 14 '14 21:04 ThiefMaster

@ThiefMaster can you make this into pull-request with tests included?

gulbinas avatar Sep 10 '14 12:09 gulbinas