1 # frozen_string_literal: true
5 "Business Description:", "Additional Keywords:"
8 MAX_DESCRIPTION_LENGTH = 500
10 def self.new(format, text)
12 when "html" then HTML.new(text || "")
13 when "markdown" then Markdown.new(text || "")
14 when "text" then Text.new(text || "")
19 include ActionView::Helpers::TextHelper
20 include ActionView::Helpers::OutputSafetyHelper
22 def sanitize(text, _options = {})
23 Sanitize.clean(text, Sanitize::Config::OSM).html_safe
28 include ActionView::Helpers::TagHelper
34 doc = Nokogiri::HTML(to_html)
39 doc.xpath("//a").each do |link|
41 link_size += link.content.length
44 link_proportion = link_size.to_f / doc.content.length
47 spammy_phrases = SPAMMY_PHRASES.count do |phrase|
48 doc.content.include?(phrase)
51 ([link_proportion - 0.2, 0.0].max * 200) +
70 def simple_format(text)
71 SimpleFormat.new.simple_format(text, :dir => "auto")
75 Sanitize.clean(text, Sanitize::Config::OSM).html_safe
78 def linkify(text, mode = :urls)
79 link_attr = tag_builder.tag_options(:rel => "nofollow noopener noreferrer")
80 Rinku.auto_link(ERB::Util.html_escape(text), mode, link_attr) do |url|
81 %r{^https?://([^/]*)(.*)$}.match(url) do |m|
82 "#{Settings.linkify_hosts_replacement}#{m[2]}" if Settings.linkify_hosts_replacement &&
83 Settings.linkify_hosts&.include?(m[1])
91 linkify(sanitize(simple_format(self)))
101 linkify(sanitize(document.to_html), :all)
109 @image_element = first_image_element(document.root) unless defined? @image_element
110 @image_element.attr["src"] if @image_element
114 @image_element = first_image_element(document.root) unless defined? @image_element
115 @image_element.attr["alt"] if @image_element
119 return @description if defined? @description
121 @description = first_truncated_text_content(document.root)
127 @document ||= Kramdown::Document.new(self)
130 def first_image_element(element)
131 return element if image?(element) && element.attr["src"].present?
133 element.children.find do |child|
134 nested_image = first_image_element(child)
135 break nested_image if nested_image
139 def first_truncated_text_content(element)
140 if paragraph?(element)
141 truncated_text_content(element)
143 element.children.find do |child|
144 text = first_truncated_text_content(child)
145 break text unless text.nil?
150 def truncated_text_content(element)
153 append_text = lambda do |child|
154 if child.type == :text
157 child.children.each do |c|
159 break if text.length > MAX_DESCRIPTION_LENGTH
163 append_text.call(element)
165 return nil if text.blank?
167 text.truncate(MAX_DESCRIPTION_LENGTH)
171 element.type == :img || (element.type == :html_element && element.value == "img")
174 def paragraph?(element)
175 element.type == :p || (element.type == :html_element && element.value == "p")
181 linkify(simple_format(ERB::Util.html_escape(self)))