Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an existing I18N translation for booleans?

I need to display "Yes" or "No" in various languages based on whether a expression is true or false. Currently I am doing it like this:

fr.yml:

fr:
  "yes": Oui
  "no": Non

a helper method:

def t_boolean(expression)
  (expression) ? t("yes") : t("no")
end

erb:

Valid: <%= t_boolean(something.is_valid?) %>

Is there some better way to do this?

Does Rails already have translations for true/false like this?

like image 808
Zabba Avatar asked Mar 08 '11 05:03

Zabba


3 Answers

After reading this, I got inspired and figured out this solution:

fr.yml

fr:
  "true": Oui
  "false": Non

erb:

Valid: <%= t something.is_valid?.to_s %>

Update

For english, if you want to use yes and no as values, be sure to quote them:

en.yml

en:
  "true": "yes"
  "false": "no"
like image 170
Zabba Avatar answered Oct 29 '22 09:10

Zabba


Just as Zabba says works fine, but if you are trying to translate true-false into yes-no, quote both sides, else you'll get true translated into true (TrueClass) again.

en:
  "true": "yes"
  "false": "no"
like image 10
Fede Borgnia Avatar answered Oct 29 '22 11:10

Fede Borgnia


You may try overriding I18n's default translate method, delegating to the default method to do the actual translation. Use this code in an initializer:

module I18n
  class << self
    alias :__translate :translate #  move the current self.translate() to self.__translate()
    def translate(key, options = {})
      if key.class == TrueClass || key.class == FalseClass
        return key ? self.__translate("yes", options) : self.__translate("no", options)
      else
        return self.__translate(key, options)
      end
    end
  end
end
like image 1
Michelle Tilley Avatar answered Oct 29 '22 10:10

Michelle Tilley