locale.rb 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. file = Rails.root.join('config/locales.yml')
  46. return false if !File.exist?(file)
  47. data = YAML.load_file(file)
  48. to_database(data)
  49. true
  50. end
  51. =begin
  52. fetch locales from remote and store them in local file system
  53. all:
  54. Locale.fetch
  55. =end
  56. def self.fetch
  57. url = 'https://i18n.zammad.com/api/v1/locales'
  58. result = UserAgent.get(
  59. url,
  60. {},
  61. {
  62. json: true,
  63. }
  64. )
  65. raise "Can't load locales from #{url}" if !result
  66. raise "Can't load locales from #{url}: #{result.error}" if !result.success?
  67. file = Rails.root.join('config/locales.yml')
  68. File.open(file, 'w') do |out|
  69. YAML.dump(result.data, out)
  70. end
  71. result.data
  72. end
  73. private_class_method def self.to_database(data)
  74. ActiveRecord::Base.transaction do
  75. data.each { |locale|
  76. exists = Locale.find_by(locale: locale['locale'])
  77. if exists
  78. exists.update(locale.symbolize_keys!)
  79. else
  80. Locale.create(locale.symbolize_keys!)
  81. end
  82. }
  83. end
  84. end
  85. end