Module: TempmailSdk::HtmlUtils

Defined in:
lib/tempmail_sdk/html_utils.rb

Overview

HTML 文本提取辅助

Class Method Summary collapse

Class Method Details

.escape(text) ⇒ String

转义 HTML 特殊字符

Parameters:

  • text (String)

Returns:

  • (String)


24
25
26
27
28
29
30
# File 'lib/tempmail_sdk/html_utils.rb', line 24

def escape(text)
  text.to_s
      .gsub("&", "&")
      .gsub("<", "&lt;")
      .gsub(">", "&gt;")
      .gsub('"', "&quot;")
end

.html_to_text(value) ⇒ String

将 HTML 粗略转换为纯文本:剥离 script/style,去标签,压缩空白

Parameters:

  • value (String, nil)

Returns:

  • (String)


11
12
13
14
15
16
17
18
19
# File 'lib/tempmail_sdk/html_utils.rb', line 11

def html_to_text(value)
  return "" if value.nil? || value.empty?

  s = value.gsub(%r{<script\b[^>]*>.*?</script>}mi, " ")
  s = s.gsub(%r{<style\b[^>]*>.*?</style>}mi, " ")
  s = s.gsub(/<[^>]+>/, " ")
  s = unescape_entities(s)
  s.split.join(" ")
end

.unescape_entities(text) ⇒ Object

反转义常见 HTML 实体



33
34
35
36
37
38
39
40
# File 'lib/tempmail_sdk/html_utils.rb', line 33

def unescape_entities(text)
  text.gsub("&amp;", "&")
      .gsub("&lt;", "<")
      .gsub("&gt;", ">")
      .gsub("&quot;", '"')
      .gsub("&#39;", "'")
      .gsub("&nbsp;", " ")
end