Rails 如何過濾你要的 HTML tag 內容

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
1.02K   0  
·
2018/11/26
·
3 mins read


一些看是很簡單的要求,實務上,卻可能很不簡單!

我現在就碰到一個很簡單的要求,就是把一個 HTML 內容做一份字數限制的簡述「summary」,很直覺的就是很簡單嘛,就移除所有的 HTML tags,在抓前幾個字就好了,不過就是一行碼:

truncate(strip_tags(html內容).squish, length: 180)

這麼簡單的一行碼就移除所有的 html tag,前後與連續的空白,再切掉超過的部分,很簡單啊,不過,馬上就遇到很多問題了,客戶說:表格不要、照片的說明不要、程式碼不要⋯⋯

那要怎麼做呢?我們就已以下這個 HTML fragment 來測試:

<p>testing table</p>
<table>
  <tbody>
    <tr>
      <td><strong>名</strong></td>
      <td><strong>姓</strong></td>
    </tr>
  </tbody>
</table>
<p>copy and paste</p>

這個 html fragment 很簡單,就是 p 跟 table,我們要做的實驗也很簡單,就是只要 <p> 不要 <table>,很直覺得,我們就是用個 Rails 內建 helper:sanitize,在 Rails 的文件中,也說可以很簡單的選擇客製化的 whitelisted tags 選擇:

scrubber = Loofah::Scrubber.new do |node|
  node.remove if node.name == 'table'
end
x_string = sanitize html_fragment, tags: %w(p), attributes: %w(), scrubber: scrubber

這個 sanitize 很清楚的要求要移出 table,只保留在tags 中指定的 html tags,輸出的結果還不錯:

<p>testing table</p>
<p>copy and paste</p>

那要是用網路上很多人推薦的 sanitize gem 呢?

rgrove/sanitize — Whitelist-based Ruby HTML and CSS sanitizer. Contribute to rgrove/sanitize development by creating an account on GitHub. Go to GitHub

它更簡單好用,只要指定你要留下來的 tags ⋯⋯

x_string = Sanitize.fragment(x_content, :elements => ['p'])

只可惜,它是把不要的 tag 去除掉了,但沒有去掉裡面的內容,這是他的輸出:

<p>testing table</p>


<p>copy and paste</p>

所以,sanitize gem 並不合我們的需求,rails內建的 sanitize 是我們要的,但是,對不同的情境,就要看不同的需求了,也許,sanitize gem 大合您意。

另一個做法可以用 nokogiri,它幾乎沒有限制,但是,有種殺雞用牛刀的感覺,而且,會有很多行的碼,我不是很喜歡。

有一個要注要的是,很多這類的程式碼都會被用在 helper 中,當用 rails c 去測試時,必須要 ApplicationController.helpers.my_method(parameter)  再加上 reload!,helper 只是一個住在記憶體中的 instant,還蠻討厭的。

不過真要做一個能簡述「summary」其實絕不是以上所說的那麼簡單,真正要做到有意義的簡述,就必須要用到 AI 人工智慧,google 有一個開發案用 tensorflow 來做文章的簡述 tensorflow,也有很多 github 的開源在做這個,例如:sumy,Readability 等等,ruby 的世界在 AI 好像沒有那麼多案子,可以確定的是,這會是一個很有趣也很有未來的挑戰,以後,看能不能用 AI 來幫忙學生交讀書心得,哈哈哈哈哈!


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

This article is part of:
Categories:
Tags:
Total: 706 words


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.