Class: ExcerptParser

Inherits:
Nokogiri::XML::SAX::Document
  • Object
show all
Defined in:
lib/excerpt_parser.rb

Constant Summary collapse

CUSTOM_EXCERPT_REGEX =
/<\s*(span|div)[^>]*class\s*=\s*['"]excerpt['"][^>]*>/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length, options = nil) ⇒ ExcerptParser

Returns a new instance of ExcerptParser.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/excerpt_parser.rb', line 8

def initialize(length, options = nil)
  @length = length
  @excerpt = +""
  @current_length = 0
  options || {}
  @strip_links = options[:strip_links] == true
  @strip_images = options[:strip_images] == true
  @text_entities = options[:text_entities] == true
  @markdown_images = options[:markdown_images] == true
  @keep_newlines = options[:keep_newlines] == true
  @keep_emoji_images = options[:keep_emoji_images] == true
  @keep_onebox_source = options[:keep_onebox_source] == true
  @keep_onebox_body = options[:keep_onebox_body] == true
  @keep_quotes = options[:keep_quotes] == true
  @keep_svg = options[:keep_svg] == true
  @remap_emoji = options[:remap_emoji] == true
  @start_excerpt = false
  @start_hashtag_icon = false
  @in_details_depth = 0
  @summary_contents = +""
  @detail_contents = +""
end

Instance Attribute Details

#excerptObject (readonly)

Returns the value of attribute excerpt.



4
5
6
# File 'lib/excerpt_parser.rb', line 4

def excerpt
  @excerpt
end

Class Method Details

.get_excerpt(html, length, options) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/excerpt_parser.rb', line 31

def self.get_excerpt(html, length, options)
  html ||= ""
  length = html.length if html.include?("excerpt") && CUSTOM_EXCERPT_REGEX === html
  me = self.new(length, options)
  parser = Nokogiri::HTML::SAX::Parser.new(me)
  catch(:done) { parser.parse(html) }
  excerpt = me.excerpt.strip
  excerpt = excerpt.gsub(/\s*\n+\s*/, "\n\n") if options[:keep_onebox_source] ||
    options[:keep_onebox_body]
  excerpt = CGI.unescapeHTML(excerpt) if options[:text_entities] == true
  excerpt
end

Instance Method Details

#characters(string, truncate: true, count_it: true, encode: true, before_string: nil, after_string: nil) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/excerpt_parser.rb', line 205

def characters(
  string,
  truncate: true,
  count_it: true,
  encode: true,
  before_string: nil,
  after_string: nil
)
  return if @in_quote

  # we call length on this so might as well ensure we have a string
  string = string.to_s
  if @in_details_depth > 0
    if @in_summary
      @summary_contents << string
    else
      @detail_contents << string
    end
    return
  end

  @excerpt << before_string if before_string

  encode = encode ? lambda { |s| ERB::Util.html_escape(s) } : lambda { |s| s }
  if count_it && @current_length + string.length > @length
    length = [0, @length - @current_length - 1].max
    @excerpt << encode.call(string[0..length]) if truncate && !emoji?(string)
    @excerpt << (@text_entities ? "..." : "&hellip;")
    @excerpt << "</a>" if @in_a
    @excerpt << after_string if after_string
    throw :done
  end

  @excerpt << encode.call(string)
  @excerpt << after_string if after_string
  @current_length += string.length if count_it
end

#clean(str) ⇒ Object



201
202
203
# File 'lib/excerpt_parser.rb', line 201

def clean(str)
  ERB::Util.html_escape(str.strip)
end

#emoji?(string) ⇒ Boolean

Returns:

  • (Boolean)


243
244
245
# File 'lib/excerpt_parser.rb', line 243

def emoji?(string)
  string.match?(/\A:\w+:\Z/)
end

#end_element(name) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/excerpt_parser.rb', line 148

def end_element(name)
  case name
  when "a"
    unless @strip_links
      characters("</a>", truncate: false, count_it: false, encode: false)
      @in_a = false
    end
  when "p", "br"
    if @keep_newlines
      characters("<br>", truncate: false, count_it: false, encode: false)
    else
      characters(" ")
    end
  when "aside"
    @in_quote = false
  when "details"
    @in_details_depth -= 1
    if @in_details_depth == 0
      @summary_contents = clean(@summary_contents)
      @detail_contents = clean(@detail_contents)

      if @current_length + @summary_contents.length >= @length
        characters(
          @summary_contents,
          encode: false,
          before_string: "<details class='disabled'><summary>",
          after_string: "</summary></details>",
        )
      else
        characters(
          @summary_contents,
          truncate: false,
          encode: false,
          before_string: "<details><summary>",
          after_string: "</summary>",
        )

        characters(@detail_contents, encode: false, after_string: "</details>")
      end
    end
  when "summary"
    @in_summary = false if @in_details_depth == 1
  when "div", "span"
    throw :done if @start_excerpt
    characters("</span>", truncate: false, count_it: false, encode: false) if @start_hashtag_icon
  when "svg"
    characters("</svg>", truncate: false, count_it: false, encode: false) if @keep_svg
    @in_svg = false
  when "use"
    characters("</use>", truncate: false, count_it: false, encode: false) if @keep_svg
  end
end

#escape_attribute(v) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/excerpt_parser.rb', line 44

def escape_attribute(v)
  return "" unless v

  v = v.dup
  v.gsub!("&", "&amp;")
  v.gsub!("\"", "&#34;")
  v.gsub!("<", "&lt;")
  v.gsub!(">", "&gt;")
  v
end

#include_tag(name, attributes) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/excerpt_parser.rb', line 55

def include_tag(name, attributes)
  characters(
    "<#{name} #{attributes.map { |k, v| "#{k}=\"#{escape_attribute(v)}\"" }.join(" ")}>",
    truncate: false,
    count_it: false,
    encode: false,
  )
end

#start_element(name, attributes = []) ⇒ Object



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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/excerpt_parser.rb', line 64

def start_element(name, attributes = [])
  case name
  when "img"
    attributes = Hash[*attributes.flatten]

    if attributes["class"]&.include?("emoji")
      if @remap_emoji
        title = (attributes["alt"] || "").gsub(":", "")
        title = Emoji.lookup_unicode(title) || attributes["alt"]
        return characters(title)
      elsif @keep_emoji_images
        return include_tag(name, attributes)
      else
        return characters(attributes["alt"])
      end
    end

    unless @strip_images
      # If include_images is set, include the image in markdown
      characters("!") if @markdown_images

      if !attributes["alt"].blank?
        characters("[#{attributes["alt"]}]")
      elsif !attributes["title"].blank?
        characters("[#{attributes["title"]}]")
      else
        characters("[#{I18n.t "excerpt_image"}]")
      end

      characters("(#{attributes["src"]})") if @markdown_images
    end
  when "a"
    unless @strip_links
      include_tag(name, attributes)
      @in_a = true
    end
  when "aside"
    attributes = Hash[*attributes.flatten]
    if !(@keep_onebox_source || @keep_onebox_body) || !attributes["class"]&.include?("onebox")
      @in_quote = true
    end

    if attributes["class"]&.include?("quote")
      if @keep_quotes || (@keep_onebox_body && attributes["data-topic"].present?)
        @in_quote = false
      end
    end
  when "article"
    @in_quote = !@keep_onebox_body if attributes.include?(%w[class onebox-body])
  when "header"
    @in_quote = !@keep_onebox_source if attributes.include?(%w[class source])
  when "div", "span"
    attributes = Hash[*attributes.flatten]

    # Only match "excerpt" class if it does not specifically equal "excerpt
    # hidden" in order to prevent internal links with GitHub oneboxes from
    # being empty https://meta.discourse.org/t/269436
    if attributes["class"]&.include?("excerpt") && !attributes["class"]&.match?("excerpt hidden")
      @excerpt = +""
      @current_length = 0
      @start_excerpt = true
    elsif attributes["class"]&.include?("hashtag-icon-placeholder")
      @start_hashtag_icon = true
      include_tag(name, attributes)
    end
  when "details"
    @detail_contents = +"" if @in_details_depth == 0
    @in_details_depth += 1
  when "summary"
    if @in_details_depth == 1 && !@in_summary
      @summary_contents = +""
      @in_summary = true
    end
  when "svg"
    attributes = Hash[*attributes.flatten]
    if attributes["class"]&.include?("d-icon") && @keep_svg
      include_tag(name, attributes)
      @in_svg = true
    end
  when "use"
    include_tag(name, attributes) if @in_svg && @keep_svg
  end
end