trabajo-afectivo/app/models/text_module.rb

77 lines
1.9 KiB
Ruby
Raw Normal View History

2022-01-01 13:38:12 +00:00
# Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
2012-10-22 13:00:26 +00:00
class TextModule < ApplicationModel
include ChecksClientNotification
include ChecksHtmlSanitized
include CanCsvImport
validates :name, presence: true
validates :content, presence: true
2016-07-25 20:13:38 +00:00
before_create :validate_content
before_update :validate_content
sanitized_html :content, :note
csv_delete_possible true
has_and_belongs_to_many :groups, after_add: :cache_update, after_remove: :cache_update, class_name: 'Group'
association_attributes_ignored :user
2016-07-25 20:13:38 +00:00
=begin
import text modules from i18n/text_modules/*.yml if no text modules exist yet.
2016-07-25 20:13:38 +00:00
TextModule.load('de-de') # e. g. 'en-us' or 'de-de'
2016-07-25 20:13:38 +00:00
=end
def self.load(locale)
raise __('Got no locale') if locale.blank?
return if !TextModule.count.zero?
2016-07-25 20:13:38 +00:00
locale = locale.split(',').first.downcase # in case of accept_language header is given
2016-07-25 20:13:38 +00:00
# First check the full locale, e.g. 'de-de'.
filename = Rails.root.join("i18n/text_modules/#{locale}.yml")
if !File.exist?(filename)
# Fall back to the more generic language if needed, e.g. 'de'.
locale = locale.split('-').first
filename = Rails.root.join("i18n/text_modules/#{locale}.yml")
2016-07-25 20:13:38 +00:00
end
if !File.exist?(filename)
# No text modules available for current locale data.
return
end
2016-07-25 20:13:38 +00:00
file_content = File.read(filename)
result = Psych.load(file_content)
2016-07-25 20:13:38 +00:00
raise "Can't load text modules from #{filename}" if result.length.zero?
ActiveRecord::Base.transaction do
result.each do |text_module|
text_module[:updated_by_id] = 1
text_module[:created_by_id] = 1
TextModule.create(text_module.symbolize_keys!)
end
2016-07-25 20:13:38 +00:00
end
true
end
private
def validate_content
return true if content.blank?
return true if content.match?(%r{<.+?>})
content.gsub!(%r{(\r\n|\n\r|\r)}, "\n")
self.content = content.text2html
true
end
end