Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i18n with Enumerize gem

I am using Enumerize gem https://github.com/brainspec/enumerize/ It allows me use beautiful selects in form with siple form. And all options in this selects are translated.

en:
  enumerize:
    user:
      sex:
        male: 'Man'
        female: 'Woman'

So, in my form I have select with variants 'Man' and 'Woman'. When I save the record with 'Man' value I get sex attribute with 'male' value. Now I want to display this value as 'Man' on the show page, but

= @user.sex

outputs as 'male' instead of 'Man'

like image 789
Kindoloki Avatar asked Feb 22 '14 18:02

Kindoloki


2 Answers

I'd probably use the .text method (you can see it inside the Gem by using bundle open enumerize and traversing the code a bit)

= @user.sex.text

You can also use the full translation key

= t("activerecord.enumerize.user.sex.#{@user.sex}")
like image 74
mlkmt Avatar answered Oct 13 '22 11:10

mlkmt


If you put the selectable values in your yaml file, like

simple_form:
  options:
    user:
      gender:
        male: Male
        female: Female

simple form will pick them up for you. No need to do any explicit translation in your view

See https://github.com/plataformatec/simple_form#i18n for more information!

To have the same level of "automation" in your other views, you could create a simple helper method that does the translation for you

def translate(record, attr)
  model = record.class.name.underscore
  value = record.send(attr)
  I18n.t("simple_form.options.#{model}.#{attr}.#{value}")
end

which you can call as

= translate(@user, :sex)
like image 30
Danny Avatar answered Oct 13 '22 11:10

Danny