2014-02-06 27 views
0

如果用戶在評論中插入了鏈接,則需要將該鏈接剪切爲20個字符。只顯示評論中的鏈接的短小部分

如何製作它?

例如:

Lorem ipsum: https://github.com/plataformatec/devise 

應當變成這樣。

Lorem ipsum: https://github.com/plataforma... 
+0

你可以顯示你的樣品輸入和樣品輸出。 – vee

+0

@vee 用戶輸入正常評論,並輸入需要中斷的鏈接。 例如: 'Lorem ipsum:https:// github.com/plataformatec/devise' 它應該是如此。 'Lorem ipsum:https://github.com/plataforma ...' – vadus

回答

1

向被截斷,您可以使用內置的字符串功能

<%= link[0..19] %> 

如果你想把它當的link_to的一部分,但想也許像上導航的全鏈路輸出文本:

<%= link_to link[0..19], url_for(link) %> 
+0

我需要切斷鏈接,如果它出現在評論處。 爲此,我認爲是必要的回調? – vadus

2

從什麼目的你想截斷?

使用String#[]你可以從任何最終得到子:

s = "string with more than twenty characters" 
s[0, 20] # get the first 20 characters 
=> "string with more tha" 
s[s.size-20, s.size] # the last 20 characters 
=> "an twenty characters" 

的Rails還增加了truncate方法字符串:

"string with more than twenty characters".truncate(20) 
=> "string with more ..." 
"string with more than twenty characters".truncate(20, omission: "") 
=> "string with more tha" 

希望有所幫助。