[英]Ruby / Rails - Generate hyperlinks from words/phrases at render time?
我已經搜索了相當多的答案,但我一直在尋找有關如何將純文本鏈接轉換為可點擊的超鏈接或從文本中刪除超鏈接的文章。 這兩者都不是。
我希望能夠在運行時解析單詞/短語,並根據一些后端邏輯/數據從它們創建超鏈接。 例如,用戶個人資料可能包含“關於我”部分,如下所示:
I went to xyz university and like basketball & football.
我想要一些可以創建超鏈接的功能:
用戶可以隨時通過不同的體育,音樂等改變他/她的個人資料,我希望能夠解釋這一點。 如果單詞/短語列表中不存在單詞或短語我指定鏈接,則沒有任何反應。
是否有一個術語我應該谷歌搜索,一些隱藏的Ruby類,這樣做,或在那里我找不到的寶石?
我感謝您提供的任何幫助!
凱爾
我想首先談談機器學習的主題,特別是關鍵詞匹配。
我不確定最好的方法,但我的出發點可能是做一些嚴格索引的postgres關鍵字搜索,並包含一個給你路由的屬性。 您將不得不構建某種類型的鍵,值查找,並且您可能必須自己開始構建字典,因為我不確定如何基於單詞獲取主觀信息。
8一種方法......其他人可能會提出一些改進......
創建一個名為Substitutions的Model和表,其中包含以下字段:phrase,hyperlink,phrase_length(在保存之前計算phrase_length)...
# look for substitions in descending phrase length order
# so that "Columbus University" is substituted instead of "Columbus" (the city)
# replace matched phrase with a temporary eyecatcher storing substitution id
# we do this so that other matches of smaller strings will disregard
# already matched text
Substitution.order("phrase_length DESC").each do |subst|
paragraph.sub!( subst.phrase, "{subbing#{subst.id.to_s.rjust(8, '0')}}" )
end
# now replace eyecatchers with hyperlink string
pointer = paragraph.index '{subbing'
while pointer
subst = Substitution.find(paragraph[pointer+9, 8].to_i)
paragraph.sub!( "{subbing#{subst.id.to_s.rjust(8, '0')}}", subst.hyperlink )
pointer = paragraph.index '{subbing' # continue while eyecatchers still present
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.