这听起来像你想利用网站上的一个给定的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