ruby-on-railsrubymobility

How to get changed attributes without locale suffixes in Mobility gem?


The documentation about dirty tracking in the mobility gem states that:

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.

So the result of #changed would look like this

post.changed
#=> ["title_en", "title_zh_cn", "body_en"]

However, I would like to get a simplified array of the attributes that were changed, without suffixes, like so:

#=> ["title", "body"]

How should I go about doing that other than manipulating the result of #changed?

Thanks, Simon.


Solution

  • UPDATE (2019/10/24)

    I realized it's actually a bit simpler, since the changes presumably happened in the current locale. In that case, you can simply strip the locale accessor from attributes (assuming any untranslated attributes don't have weird names with locale extensions on them):

    post.changed.map { |attr| attr.gsub(/_#{Mobility.normalized_locale}$/, '') }
    

    ORIGINAL ANSWER

    How about:

    post.changed.map { |attr| attr.gsub /_([a-z]{2}(_[a-z]{2})?)/, ''}.uniq
    #=> ["title", "body"]