Class: Goethe::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/goethe/utils.rb

Class Method Summary collapse

Class Method Details

从文本中找到链接,转化为 ‘<a>` 标签,找到换行符,转换为 `
` 标签

Parameters:

  • str (String)

Returns:

  • (String)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/goethe/utils.rb', line 14

def auto_link(str)
  str = str.dup
  str.gsub!(/<(S*?)[^>]*>.*?|<.*? \/>/) do |s|
    s.gsub!(/</, "&lt;")
    s.gsub!(/>/, "&gt;")
  end

  str.gsub!(/((https|http|ftp):\/\/)([a-zA-Z0-9.\-_%&=\/\#:\?]+)/i) do
    protocol, url = $1, $3
    %Q{<a href="#{protocol}#{url}" rel="nofollow" target="_blank">#{protocol}#{url}</a>}
  end

  str.gsub!(/\r\n|\n/, "<br>")
  str
end

.remove_html_tags(str, replacement: " ") ⇒ String

替换文本中所有的 HTML 标签,默认替换成空格

Parameters:

  • str (String)
  • replacement (String) (defaults to: " ")
    • 替换的字符,默认是空格

Returns:

  • (String)


38
39
40
41
42
# File 'lib/goethe/utils.rb', line 38

def remove_html_tags(str, replacement: " ")
  return "" if str.nil?
  str.gsub(Goethe::Regex[:HTML_TAGS], replacement)
    .gsub(Goethe::Regex[:ADDITIONAL_HTML_TAG], replacement)
end

.remove_markdown_symbols(str) ⇒ String

移除文本中所有的 Markdown 控制字符

Parameters:

  • str (String)

Returns:

  • (String)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/goethe/utils.rb', line 51

def remove_markdown_symbols(str)
  return "" if str.nil?

  result = ""

  # HEADERS
  result = str.gsub(Goethe::Regex[:MARKDOWN][:HEADERS], "")
  #p "HEADERS: #{result}, #{result.size}"


  result = result.gsub(Goethe::Regex[:MARKDOWN][:BLOCKQUOTES], "")
  #p "BLOCKQUOTES: #{result}, #{result.size}"


  # RULERS
  result = result.gsub(Goethe::Regex[:MARKDOWN][:HRULERS], "") do
    $2
  end
  #p "RULERS: #{result}, #{result.size}"

  # LISTS
  result = result.gsub(Goethe::Regex[:MARKDOWN][:LISTS], "")
  #p "LISTS: #{result}, #{result.size}"

  # EMPHASIS
  result = result.gsub(Goethe::Regex[:MARKDOWN][:EMPHASIS]) do
    $2
  end


  # IMAGES
  result = result.gsub(Goethe::Regex[:MARKDOWN][:IMAGES], "")


  # LINKs
  result = result.gsub(Goethe::Regex[:MARKDOWN][:LINKS]) do
    $1
  end

  # COPYRIGHT
  result = result.gsub(Goethe::Regex[:MARKDOWN][:COPYRIGHT], "")

  # <quock_link>
  result = result.gsub(Goethe::Regex[:MARKDOWN][:QUICK_LINKS]) do
    " #{$1} "
  end

  result
end