如何在 Mobility gem 中获取没有语言环境后缀的更改属性?
How to get changed attributes without locale suffixes in Mobility gem?
移动 gem 中关于 dirty tracking 的文档指出:
Mobility uses locale suffixes to indicate which locale has changed; dirty tracking is implemented this way to ensure that it is clear what has changed in which locale, avoiding any possible ambiguity.
所以 #changed
的结果看起来像这样
post.changed
#=> ["title_en", "title_zh_cn", "body_en"]
但是,我想获得一个简化的已更改属性数组,不带后缀,如下所示:
#=> ["title", "body"]
除了操纵 #changed
的结果外,我应该怎么做?
谢谢,
西蒙.
更新 (2019/10/24)
我意识到它实际上有点简单,因为更改可能发生在当前语言环境中。在这种情况下,您可以简单地从属性中删除语言环境访问器(假设任何未翻译的属性没有带有语言环境扩展名的奇怪名称):
post.changed.map { |attr| attr.gsub(/_#{Mobility.normalized_locale}$/, '') }
原始答案
怎么样:
post.changed.map { |attr| attr.gsub /_([a-z]{2}(_[a-z]{2})?)/, ''}.uniq
#=> ["title", "body"]
移动 gem 中关于 dirty tracking 的文档指出:
Mobility uses locale suffixes to indicate which locale has changed; dirty tracking is implemented this way to ensure that it is clear what has changed in which locale, avoiding any possible ambiguity.
所以 #changed
的结果看起来像这样
post.changed
#=> ["title_en", "title_zh_cn", "body_en"]
但是,我想获得一个简化的已更改属性数组,不带后缀,如下所示:
#=> ["title", "body"]
除了操纵 #changed
的结果外,我应该怎么做?
谢谢, 西蒙.
更新 (2019/10/24)
我意识到它实际上有点简单,因为更改可能发生在当前语言环境中。在这种情况下,您可以简单地从属性中删除语言环境访问器(假设任何未翻译的属性没有带有语言环境扩展名的奇怪名称):
post.changed.map { |attr| attr.gsub(/_#{Mobility.normalized_locale}$/, '') }
原始答案
怎么样:
post.changed.map { |attr| attr.gsub /_([a-z]{2}(_[a-z]{2})?)/, ''}.uniq
#=> ["title", "body"]