2014-02-07 58 views
0

我遇到问题。检测网站视频的链接并显示标题

我有一个视频和评论模型。 如果用户将视频链接插入到评论中,则链接将替换为来自视频的标题。

我该怎么写一个方法?

def to_show_title_instead_of_the_link 
    body.gsub!(%r{(videos)\/([0-9])}) {|link| link_to link)} 
end 

我们输入:

http://localhost:3000/videos/1 

我们得到:

<a href="http://localhost:3000/videos/1"> test video</a> 
+0

你需要什么正则表达式来匹配“测试视频”? – cortex

+0

@cortex no。而不是链接应该有一个标题。 – vadus1

回答

2

这听起来像你想利用网站上的一个给定的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!的理解,并测试了我上面=写的正则表达式)

+0

感谢您的建议,我认为这是我需要的。 – vadus1

+0

没问题!我实际上只是多想一点,并不是在整个'body'文本上运行这个方法的最简单的方法。我们应该使用它作为评论视图的辅助方法,并为评论的文本运行正则表达式。我更新了答案,向你展示了我的意思。 –

+1

我明白了,再次感谢。我会处理你的方法,我会写他的版本。 – vadus1

1

我并重构代码,并使用了宝石rinku

def links_in_body(text) 
    auto_link(text) do |url| 
    video_id = url.match(/\Ahttps?:\/\/#{request.host_with_port}\/videos\/(\d+)\z/) 
    if video_id.present? 
     Video.find(video_id[1]).title 
    else 
     truncate(url, length: AppConfig.truncate.length) 
    end 
    end 
end 
相关问题