Fix translation_hybrid locale caster
This commit is contained in:
@@ -4,6 +4,12 @@ Changelog
|
||||
Here you can see the full list of changes between each SQLAlchemy-Utils release.
|
||||
|
||||
|
||||
0.30.10 (2015-06-17)
|
||||
^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
- Added better support for dynamic locales in translation_hybrid
|
||||
|
||||
|
||||
0.30.9 (2015-06-09)
|
||||
^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
|
@@ -115,4 +115,39 @@ of translation_hybrid. In the following example we make translation hybrid fallb
|
||||
|
||||
Article().name # ''
|
||||
|
||||
|
||||
Dynamic locales
|
||||
---------------
|
||||
|
||||
Sometimes locales need to be dynamic. The following example illustrates how to setup
|
||||
dynamic locales.
|
||||
|
||||
|
||||
::
|
||||
|
||||
translation_hybrid = TranslationHybrid(
|
||||
current_locale=get_locale,
|
||||
default_locale=lambda obj: obj.locale,
|
||||
)
|
||||
|
||||
|
||||
class Article(Base):
|
||||
__tablename__ = 'article'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
name_translations = Column(HSTORE)
|
||||
|
||||
name = translation_hybrid(name_translations, default)
|
||||
locale = Column(String)
|
||||
|
||||
|
||||
article = Article(name_translations={'en': 'Some article'})
|
||||
session.add(article)
|
||||
session.commit()
|
||||
|
||||
article.name # Some article (even if current locale is other than 'en')
|
||||
|
||||
|
||||
|
||||
|
||||
.. _SQLAlchemy-i18n: https://github.com/kvesteri/sqlalchemy-i18n
|
||||
|
@@ -3,6 +3,9 @@ from sqlalchemy.ext.hybrid import hybrid_property
|
||||
|
||||
from .exceptions import ImproperlyConfigured
|
||||
|
||||
from babel import Locale
|
||||
|
||||
|
||||
try:
|
||||
from babel.dates import get_day_names
|
||||
except ImportError:
|
||||
@@ -37,10 +40,12 @@ class TranslationHybrid(object):
|
||||
"""
|
||||
if callable(locale):
|
||||
try:
|
||||
return str(locale())
|
||||
locale = locale()
|
||||
except TypeError:
|
||||
return str(locale(obj))
|
||||
return str(locale)
|
||||
locale = locale(obj)
|
||||
if isinstance(locale, Locale):
|
||||
return str(locale)
|
||||
return locale
|
||||
|
||||
def getter_factory(self, attr):
|
||||
"""
|
||||
|
@@ -65,3 +65,21 @@ class TestTranslationHybrid(TestCase):
|
||||
self.session.commit()
|
||||
|
||||
assert self.session.query(self.City.name).scalar() == name
|
||||
|
||||
def test_dynamic_locale(self):
|
||||
self.translation_hybrid = TranslationHybrid(
|
||||
lambda obj: obj.locale,
|
||||
'fi'
|
||||
)
|
||||
|
||||
class Article(self.Base):
|
||||
__tablename__ = 'article'
|
||||
id = sa.Column(sa.Integer, primary_key=True)
|
||||
name_translations = sa.Column(HSTORE)
|
||||
name = self.translation_hybrid(name_translations)
|
||||
locale = sa.Column(sa.String)
|
||||
|
||||
assert (
|
||||
'coalesce(article.name_translations -> article.locale'
|
||||
in str(Article.name)
|
||||
)
|
||||
|
Reference in New Issue
Block a user