-1

I have a namespace in my routes:

namespace :fruit do
  resources :apple, only [:create, :destroy]
  resources :banana, only [:show]
end

and also the same key in my translation file:

en:
  fruit:
    apple:
      name: apple
    banana:
      name: banana

This works just fine, what I want to do is to be able to use a completely new key for the namespace part if my user has particular permissions (user.is_a_vendor?). So for a vendor I would like the translations to be t('vendor.apple.name') instead of t('fruit.apple.name') for example but I don't want to have to conditionally do this in all of my views. Is there a way to centrally switch the keys based on the user? This seems like there should be a simple solution but I can't seem to figure it out.

I have a lot of views that already have their keys set and they use lazy loading so I was wondering if there's a way to conditionally change the lazy loading to use a different key in the top.

EDIT:

I don't want to use my own custom locale since I might want to have translations for these in other languages other than English and if I do that, this solution would lead to problems. I also don't want to use a helper since that would check the conditional every single time, I'd rather have it just select a locale key automatically. Some more research lead me down the path of i18n custom backends: https://guides.rubyonrails.org/i18n.html#using-different-backends, https://www.rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base#eager_load!-instance_method and it might be what I need to use to do this?

Vishal Rao
  • 872
  • 1
  • 7
  • 18

2 Answers2

0

I would write a helper that did the switch for you. You then use your custom helper everywhere in your views, and within the helper decide which parent namespace you want to concatenate with the requested translation.

Jon
  • 10,678
  • 2
  • 36
  • 48
0

I think you can create a vendor locale (eg. en_vendor) then switch locale base on user type, so both cases you can keep the key t('fruit.apple.name') or lazy lookup t('.apple.name') on views, no need to change any views or replace(switch) keys at all.

# controller
around_action :switch_locale

def switch_locale(&action)
 locale = current_user.is_a_vendor? ? :en_vendor : :en #"#{I18n.locale}_vendor"? 
 I18n.with_locale(locale, &action)
end

# en.yml
en:
  fruit:
    apple:
      name: apple
    banana:
      name: banana

en_vendor:
  fruit:
    apple:
      name: apple vendor
    banana:
      name: banana vendor

In case you already had locale file for vendor, i think you can copy/paste to or organize like en.yml file above and switch locale, it takes less effort than switch keys.

Lam Phan
  • 3,405
  • 2
  • 9
  • 20