Matrix
Matrix

Reputation: 3369

Rails / I18n: How to translate constants of model?

If I have a model with constants like

class Topic < ActiveRecord::Base
  STATUS_DISABLED = 0
  STATUS_ENABLED  = 1
end

What can I do to translate it with locales?
I would like to do something like that:

en:
 Topic:
   STATUS_ENABLED: 'Enable'
   STATUS_DISABLED: 'Disable'

What is the best way to translate my models' constants?

Upvotes: 1

Views: 2416

Answers (1)

user229044
user229044

Reputation: 239312

You can't. Your YAML files have no access to Ruby-level constants, they're two different languages.

Further, you shouldn't. Constants are for use in your source-code. They have no need to be translated, you might as well ask how to localize class names.

If you want to map your symbolic constants to translatable strings, you should add a function that returns the English (or other native language) version, and then translate that.

class Topic < ActiveRecord::Base
  STATUS_DISABLED = 0
  STATUS_ENABLED  = 1

  def status_name(status)
    case status
    when CASE_DISABLED then 'disabled'
    when CASE_ENABLED then 'enabled'
    end
  end
end

Your YAML file would contain:

en:
  topic:
    enabled: 'Enable'
    disable: 'Disable'

If you have many values that you want to store as integers but translate to strings, you're probably after an enum:

class Topic
  enum status: [:disabled, :enabled]
end

This gives you access to Topic.statuses which will return [:disabled, :enabled]; you can invoke to_s on these symbols to produce the strings 'disabled' and 'enabled', which you can feed into I18n to translate.

Upvotes: 1

Related Questions