You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

i18n.rb 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2017 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. module Redmine
  19. module I18n
  20. def self.included(base)
  21. base.extend Redmine::I18n
  22. end
  23. def l(*args)
  24. case args.size
  25. when 1
  26. ::I18n.t(*args)
  27. when 2
  28. if args.last.is_a?(Hash)
  29. ::I18n.t(*args)
  30. elsif args.last.is_a?(String)
  31. ::I18n.t(args.first, :value => args.last)
  32. else
  33. ::I18n.t(args.first, :count => args.last)
  34. end
  35. else
  36. raise "Translation string with multiple values: #{args.first}"
  37. end
  38. end
  39. def l_or_humanize(s, options={})
  40. k = "#{options[:prefix]}#{s}".to_sym
  41. ::I18n.t(k, :default => s.to_s.humanize)
  42. end
  43. def l_hours(hours)
  44. hours = hours.to_f
  45. l((hours < 2.0 ? :label_f_hour : :label_f_hour_plural), :value => format_hours(hours))
  46. end
  47. def l_hours_short(hours)
  48. l(:label_f_hour_short, :value => format_hours(hours.to_f))
  49. end
  50. def ll(lang, str, arg=nil)
  51. options = arg.is_a?(Hash) ? arg : {:value => arg}
  52. locale = lang.to_s.gsub(%r{(.+)\-(.+)$}) { "#{$1}-#{$2.upcase}" }
  53. ::I18n.t(str.to_s, options.merge(:locale => locale))
  54. end
  55. # Localizes the given args with user's language
  56. def lu(user, *args)
  57. lang = user.try(:language).presence || Setting.default_language
  58. ll(lang, *args)
  59. end
  60. def format_date(date)
  61. return nil unless date
  62. options = {}
  63. options[:format] = Setting.date_format unless Setting.date_format.blank?
  64. ::I18n.l(date.to_date, options)
  65. end
  66. def format_time(time, include_date=true, user=nil)
  67. return nil unless time
  68. user ||= User.current
  69. options = {}
  70. options[:format] = (Setting.time_format.blank? ? :time : Setting.time_format)
  71. time = time.to_time if time.is_a?(String)
  72. zone = user.time_zone
  73. local = zone ? time.in_time_zone(zone) : (time.utc? ? time.localtime : time)
  74. (include_date ? "#{format_date(local)} " : "") + ::I18n.l(local, options)
  75. end
  76. def format_hours(hours)
  77. return "" if hours.blank?
  78. if Setting.timespan_format == 'minutes'
  79. h = hours.floor
  80. m = ((hours - h) * 60).round
  81. "%d:%02d" % [ h, m ]
  82. else
  83. "%.2f" % hours.to_f
  84. end
  85. end
  86. def day_name(day)
  87. ::I18n.t('date.day_names')[day % 7]
  88. end
  89. def day_letter(day)
  90. ::I18n.t('date.abbr_day_names')[day % 7].first
  91. end
  92. def month_name(month)
  93. ::I18n.t('date.month_names')[month]
  94. end
  95. def valid_languages
  96. ::I18n.available_locales
  97. end
  98. # Returns an array of languages names and code sorted by names, example:
  99. # [["Deutsch", "de"], ["English", "en"] ...]
  100. #
  101. # The result is cached to prevent from loading all translations files
  102. # unless :cache => false option is given
  103. def languages_options(options={})
  104. options = if options[:cache] == false
  105. available_locales = ::I18n.backend.available_locales
  106. valid_languages.
  107. select {|locale| available_locales.include?(locale)}.
  108. map {|lang| [ll(lang.to_s, :general_lang_name), lang.to_s]}.
  109. sort_by(&:first)
  110. else
  111. ActionController::Base.cache_store.fetch "i18n/languages_options/#{Redmine::VERSION}" do
  112. languages_options :cache => false
  113. end
  114. end
  115. options.map {|name, lang| [name.force_encoding("UTF-8"), lang.force_encoding("UTF-8")]}
  116. end
  117. def find_language(lang)
  118. @@languages_lookup ||= valid_languages.inject({}) {|k, v| k[v.to_s.downcase] = v; k }
  119. @@languages_lookup[lang.to_s.downcase]
  120. end
  121. def set_language_if_valid(lang)
  122. if l = find_language(lang)
  123. ::I18n.locale = l
  124. end
  125. end
  126. def current_language
  127. ::I18n.locale
  128. end
  129. # Custom backend based on I18n::Backend::Simple with the following changes:
  130. # * lazy loading of translation files
  131. # * available_locales are determined by looking at translation file names
  132. class Backend
  133. (class << self; self; end).class_eval { public :include }
  134. module Implementation
  135. include ::I18n::Backend::Base
  136. include ::I18n::Backend::Pluralization
  137. # Stores translations for the given locale in memory.
  138. # This uses a deep merge for the translations hash, so existing
  139. # translations will be overwritten by new ones only at the deepest
  140. # level of the hash.
  141. def store_translations(locale, data, options = {})
  142. locale = locale.to_sym
  143. translations[locale] ||= {}
  144. data = data.deep_symbolize_keys
  145. translations[locale].deep_merge!(data)
  146. end
  147. # Get available locales from the translations filenames
  148. def available_locales
  149. @available_locales ||= ::I18n.load_path.map {|path| File.basename(path, '.*')}.uniq.sort.map(&:to_sym)
  150. end
  151. # Clean up translations
  152. def reload!
  153. @translations = nil
  154. @available_locales = nil
  155. super
  156. end
  157. protected
  158. def init_translations(locale)
  159. locale = locale.to_s
  160. paths = ::I18n.load_path.select {|path| File.basename(path, '.*') == locale}
  161. load_translations(paths)
  162. translations[locale] ||= {}
  163. end
  164. def translations
  165. @translations ||= {}
  166. end
  167. # Looks up a translation from the translations hash. Returns nil if
  168. # eiher key is nil, or locale, scope or key do not exist as a key in the
  169. # nested translations hash. Splits keys or scopes containing dots
  170. # into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
  171. # <tt>%w(currency format)</tt>.
  172. def lookup(locale, key, scope = [], options = {})
  173. init_translations(locale) unless translations.key?(locale)
  174. keys = ::I18n.normalize_keys(locale, key, scope, options[:separator])
  175. keys.inject(translations) do |result, _key|
  176. _key = _key.to_sym
  177. return nil unless result.is_a?(Hash) && result.has_key?(_key)
  178. result = result[_key]
  179. result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
  180. result
  181. end
  182. end
  183. end
  184. include Implementation
  185. # Adds fallback to default locale for untranslated strings
  186. include ::I18n::Backend::Fallbacks
  187. end
  188. end
  189. end