這聽起來像你想利用網站上的一個給定的URL,並找到這條路的相關參數。這樣可以讓您以乾淨,乾爽的方式獲取視頻的id
(無需使用可能會在您的路由發生變化時稍後斷開的正則表達式)。這會讓你查找模型實例並獲取它的title
字段。此任務的Rails方法是Rails.application.routes.recognize_path
,該方法返回包含操作,控制器和路徑參數的散列。
在你看來:
# app\views\comments\show.html.erb
# ...
<div class='comment-text'>
replace_video_url_with_anchor_tag_and_title(comment.text)
</div>
# ...
這裏是輔助方法:
# app\helpers\comments_helper.rb
def replace_video_url_with_anchor_tag_and_title(comment_text)
# assuming links will end with a period, comma, exclamation point, or white space
# this will match all links on your site
# the part in parentheses are relative paths on your site
# \w matches alphanumeric characters and underscores. we also need forward slashes
regex = %r{http://your-cool-site.com(/[\w/]+)[\.,!\s]?}
comment_text.gsub(regex) do |matched|
# $1 gives us the portion of the regex captured by the parentheses
params = Rails.application.routes.recognize_path $1
# if the link we found was a video link, replaced matched string with
# an anchor tag to the video, with the video title as the link text
if params[:controller] == 'video' && params[:action] == 'show'
video = Video.find params[:id]
link_to video.title, video_path(video)
# otherwise just return the string without any modifications
else
matched
end
end
end
我不知道如何做到這一點從我的頭頂,但我就是這樣想通了:
1)谷歌rails reverse route
,第一個結果是這個stackoverflow問題:Reverse rails routing: find the the action name from the URL。答案提到ActionController::Routing::Routes.recognize_path
。我激發了rails console
並嘗試了這一點,但它已被棄用,並沒有實際工作。
2)我然後谷歌rails recognize_path
。第一個搜索結果是文檔,這不是很有幫助。第三個搜索結果是How do you use ActionDispatch::Routing::RouteSet recognize_path?,其第二個解決方案實際工作。
3)當然,我則不得不去刷新我的Ruby的正則表達式的語法和gsub!
的理解,並測試了我上面=寫的正則表達式)
你需要什麼正則表達式來匹配「測試視頻」? – cortex
@cortex no。而不是鏈接應該有一個標題。 – vadus1