Skip to content
This repository has been archived by the owner on Jul 14, 2020. It is now read-only.

set_lang is not really viable when retrieving data #176

Open
ThiefMaster opened this issue Apr 13, 2014 · 2 comments
Open

set_lang is not really viable when retrieving data #176

ThiefMaster opened this issue Apr 13, 2014 · 2 comments

Comments

@ThiefMaster
Copy link

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
Copy link
Author

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)

@gulbinas
Copy link
Collaborator

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants