locale.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Locale < ApplicationModel
  3. =begin
  4. get locals to sync
  5. all:
  6. Locale.to_sync
  7. returns
  8. ['en-us', 'de-de', ...]
  9. =end
  10. def self.to_sync
  11. locales = Locale.where(active: true)
  12. if Rails.env.test?
  13. locales = Locale.where(active: true, locale: ['en-us', 'de-de'])
  14. end
  15. # read used locales based on env, e. g. export Z_LOCALES='en-us:de-de'
  16. if ENV['Z_LOCALES']
  17. locales = Locale.where(active: true, locale: ENV['Z_LOCALES'].split(':') )
  18. end
  19. locales
  20. end
  21. =begin
  22. sync locales from local if exists, otherwise from online
  23. all:
  24. Locale.sync
  25. =end
  26. def self.sync
  27. return true if load_from_file
  28. load
  29. end
  30. =begin
  31. load locales from online
  32. all:
  33. Locale.load
  34. =end
  35. def self.load
  36. data = fetch
  37. to_database(data)
  38. end
  39. =begin
  40. load locales from local
  41. all:
  42. Locale.load_from_file
  43. =end
  44. def self.load_from_file
  45. version = Version.get
  46. file = Rails.root.join("config/locales-#{version}.yml")
  47. return false if !File.exist?(file)
  48. data = YAML.load_file(file)
  49. to_database(data)
  50. true
  51. end
  52. =begin
  53. fetch locales from remote and store them in local file system
  54. all:
  55. Locale.fetch
  56. =end
  57. def self.fetch
  58. version = Version.get
  59. url = 'https://i18n.zammad.com/api/v1/locales'
  60. result = UserAgent.get(
  61. url,
  62. {
  63. version: version,
  64. },
  65. {
  66. json: true,
  67. open_timeout: 8,
  68. read_timeout: 24,
  69. }
  70. )
  71. raise "Can't load locales from #{url}" if !result
  72. raise "Can't load locales from #{url}: #{result.error}" if !result.success?
  73. file = Rails.root.join("config/locales-#{version}.yml")
  74. File.open(file, 'w') do |out|
  75. YAML.dump(result.data, out)
  76. end
  77. result.data
  78. end
  79. private_class_method def self.to_database(data)
  80. ActiveRecord::Base.transaction do
  81. data.each do |locale|
  82. exists = Locale.find_by(locale: locale['locale'])
  83. if exists
  84. exists.update!(locale.symbolize_keys!)
  85. else
  86. Locale.create!(locale.symbolize_keys!)
  87. end
  88. end
  89. end
  90. end
  91. end