knowledge_base_rich_text_helper.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. module KnowledgeBaseRichTextHelper
  2. def prepare_rich_text(input)
  3. prepare_rich_text_videos(prepare_rich_text_links(input))
  4. end
  5. def prepare_rich_text_links(input)
  6. scrubber = Loofah::Scrubber.new do |node|
  7. next if node.name != 'a'
  8. next if !node.key? 'data-target-type'
  9. case node['data-target-type']
  10. when 'knowledge-base-answer'
  11. if (translation = KnowledgeBase::Answer::Translation.find_by(id: node['data-target-id']))
  12. path = help_answer_path(translation.answer.category.translation_preferred(translation.kb_locale),
  13. translation,
  14. locale: translation.kb_locale.system_locale.locale)
  15. node['href'] = custom_path_if_needed path, translation.kb_locale.knowledge_base
  16. else
  17. node['href'] = '#'
  18. end
  19. end
  20. end
  21. Loofah.scrub_fragment(input, scrubber).to_s.html_safe # rubocop:disable Rails/OutputSafety
  22. end
  23. def prepare_rich_text_videos(input)
  24. input.gsub(/\((\s*)widget:(\s*)video\W([\s\S])+?\)/) do |match|
  25. settings = match
  26. .slice(1...-1)
  27. .split(',')
  28. .map { |pair| pair.split(':').map(&:strip) }
  29. .to_h
  30. .symbolize_keys
  31. url = case settings[:provider]
  32. when 'youtube'
  33. "https://www.youtube.com/embed/#{settings[:id]}"
  34. when 'vimeo'
  35. "https://player.vimeo.com/video/#{settings[:id]}"
  36. end
  37. return match if !url
  38. "<div class='videoWrapper'><iframe id='#{settings[:provider]}#{settings[:id]}' type='text/html' src='#{url}' frameborder='0'></iframe></div>"
  39. end
  40. end
  41. end