Rails 的 .html_safe 跟 raw() 的差別

紅寶鐵軌客
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.23K   0  
·
2018/03/04
·
2 mins read


raw:(adj.) 未烹調的, (食物)生的

Rails 最有趣也是討厭的就是有很多幾乎相同的功能,很多時候,幾乎也就是那個用的順手,就用那個,這次我在用 .html_safe 時,就一直想,這到底跟 Raw() 有什麼不同啊?

當然,最明顯的就是用法不同,.html_safe 一看就知道是一個 string 的 method,所以用法就是:“string".html_safe,raw() 看知道,是一個 helper,所以用的時候是:raw(string)。在 Rails 的文件中,也直接就寫了:html_safe method is equivalent to the `raw` helper in views,其實,還是有點不一樣,看原始碼最清楚,這是文件中的原始碼:

# File actionview/lib/action_view/helpers/output_safety_helper.rb, line 16
def raw(stringish)
stringish.to_s.html_safe
end

所以,答案就很清楚了,raw 就是管你要轉換的是什麼,都把他轉成字串,再用 .html_safe 輸出,答案揭曉!

在使用上,如果就已經知道要轉換的是字串了,就直接用 .html_safe,如果不確定,就用 Raw(),有一點要注意的就是:

  • nil.html_safe => NoMethodError: undefined method `html_safe' for nil:NilClass
  • raw(nil) => nil.to_s.html_safe => ""

更簡單的說,用 raw 幾乎不會錯,但是,對要轉換的是已知的字串,是有點多此一舉,還有,就是不像 .html_safe 那樣望文生義的具有說自我說明性了。


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

分類於:
標籤:
日期:
創作於:2018/03/04,最後更新於:2018/03/04。
合計:320字


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.