@@ -14,25 +14,33 @@ def total_dojos_count(dojos)
1414 # 道場のノート欄でリンクを保持しながらテキストを切り詰める
1515 def truncate_with_preserved_links ( text , length : 60 )
1616 return text if text . blank?
17-
17+
1818 # まずリンクを自動検出してHTMLに変換(target="_blank"を追加)
1919 html_with_links = Rinku . auto_link ( text , :all , 'target="_blank"' )
20-
20+
2121 # HTMLをパースする
2222 doc = Nokogiri ::HTML ::DocumentFragment . parse ( html_with_links )
23-
23+
24+ # リンクの表示テキストを簡略化(href属性は保持)
25+ doc . css ( 'a' ) . each do |link |
26+ display_text = link . text
27+ # http://, https:// を削除(\A で文字列の先頭のみマッチ)
28+ display_text = display_text . gsub ( /\A https?:\/ \/ / , '' )
29+ # 末尾のスラッシュを削除(\z で文字列の末尾のみマッチ)
30+ display_text = display_text . gsub ( /\/ \z / , '' )
31+ link . content = display_text
32+ end
33+
2434 # 表示用のテキストの長さを計算
2535 visible_text = doc . text
26-
27- if visible_text . length <= length
28- # 切り詰める必要がない場合はそのまま返す
29- return html_with_links . html_safe
30- end
31-
36+
37+ # 切り詰める必要がない場合は変更後のHTMLを返す
38+ return doc . to_html . html_safe if visible_text . length <= length
39+
3240 # 切り詰める必要がある場合
3341 result = ""
3442 current_length = 0
35-
43+
3644 doc . children . each do |node |
3745 if node . text?
3846 # 通常のテキストノード
@@ -41,14 +49,14 @@ def truncate_with_preserved_links(text, length: 60)
4149 result += node . content [ 0 , remaining_length ] + "..."
4250 break
4351 else
44- result += node . content
52+ result += node . content
4553 current_length += node . content . length
4654 end
4755 elsif node . name == 'a'
4856 # リンクノード
4957 link_text = node . text
5058 remaining_length = length - current_length
51-
59+
5260 if link_text . length > remaining_length
5361 # リンクのテキスト部分を切り詰める(href属性とtarget属性を保持)
5462 truncated_text = link_text [ 0 , remaining_length ] + "..."
@@ -62,7 +70,7 @@ def truncate_with_preserved_links(text, length: 60)
6270 # その他のHTMLノード
6371 node_text = node . text
6472 remaining_length = length - current_length
65-
73+
6674 if node_text . length > remaining_length
6775 # このノード内でも切り詰めが必要
6876 result += node . text [ 0 , remaining_length ] + "..."
@@ -72,10 +80,10 @@ def truncate_with_preserved_links(text, length: 60)
7280 current_length += node_text . length
7381 end
7482 end
75-
83+
7684 break if current_length >= length
7785 end
78-
86+
7987 result . html_safe
8088 end
8189end
0 commit comments