text_module.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class TextModule < ApplicationModel
  3. include ChecksClientNotification
  4. include ChecksHtmlSanitized
  5. include CanCsvImport
  6. validates :name, presence: true
  7. validates :content, presence: true
  8. before_create :validate_content
  9. before_update :validate_content
  10. validates :note, length: { maximum: 250 }
  11. sanitized_html :content, :note
  12. csv_delete_possible true
  13. has_and_belongs_to_many :groups, after_add: :cache_update, after_remove: :cache_update, class_name: 'Group'
  14. association_attributes_ignored :user
  15. =begin
  16. import text modules from i18n/text_modules/*.yml if no text modules exist yet.
  17. TextModule.load('de-de') # e. g. 'en-us' or 'de-de'
  18. =end
  19. def self.load(locale)
  20. raise __("The required parameter 'locale' is missing.") if locale.blank?
  21. return if !TextModule.count.zero?
  22. locale = locale.split(',').first.downcase # in case of accept_language header is given
  23. # First check the full locale, e.g. 'de-de'.
  24. filename = Rails.root.join("i18n/text_modules/#{locale}.yml")
  25. if !File.exist?(filename)
  26. # Fall back to the more generic language if needed, e.g. 'de'.
  27. locale = locale.split('-').first
  28. filename = Rails.root.join("i18n/text_modules/#{locale}.yml")
  29. end
  30. if !File.exist?(filename)
  31. # No text modules available for current locale data.
  32. return
  33. end
  34. file_content = File.read(filename)
  35. result = Psych.load(file_content)
  36. raise "Can't load text modules from #{filename}" if result.empty?
  37. ActiveRecord::Base.transaction do
  38. result.each do |text_module|
  39. text_module[:updated_by_id] = 1
  40. text_module[:created_by_id] = 1
  41. TextModule.create(text_module.symbolize_keys!)
  42. end
  43. end
  44. true
  45. end
  46. private
  47. def validate_content
  48. return true if content.blank?
  49. return true if content.match?(%r{<.+?>})
  50. content.gsub!(%r{(\r\n|\n\r|\r)}, "\n")
  51. self.content = content.text2html
  52. true
  53. end
  54. end