Module: Models::Utilities::Html

Extended by:
ActiveSupport::Concern
Included in:
Article, Item, ProductLine
Defined in:
app/concerns/models/utilities/html.rb

Overview

Provides HTML cleaning and conversion utilities for models.
Included by: Item, Article, ProductLine

Instance Method Summary collapse

Instance Method Details

#clean_and_compress_html(html) ⇒ String

Removes newlines and excess whitespace from an HTML string, scrubs it
with Loofah's +prune+ scrubber, and returns the sanitized result.

Parameters:

  • html (String)

    the HTML to clean and compress

Returns:

  • (String)

    the scrubbed, whitespace-collapsed HTML



17
18
19
20
21
22
23
# File 'app/concerns/models/utilities/html.rb', line 17

def clean_and_compress_html(html)
  # Parse the HTML
  cleaned_html = html.gsub(/[\r\n]/, "").gsub(/[[:space:]]+/, " ")
  fragment = Loofah.fragment(cleaned_html)
  fragment.scrub!(:prune)
  fragment.to_s.strip
end

#html_to_text(html, remove_empty_lines: true) ⇒ String?

Converts an html to text and remove empty lines

Parameters:

  • html (String, nil)

    the HTML to convert; +nil+ or blank returns +nil+

  • remove_empty_lines (Boolean) (defaults to: true)

    whether to strip empty lines from the result

Returns:

  • (String, nil)

    the plain-text conversion, or +nil+ when +html+ is blank



30
31
32
33
34
35
36
# File 'app/concerns/models/utilities/html.rb', line 30

def html_to_text(html, remove_empty_lines: true)
  return if html.blank?

  s = ActionText::Content.new(html).to_plain_text
  s = s.lines.map(&:strip).reject(&:empty?).join("\n") if remove_empty_lines
  s
end