2014-02-07 56 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 
相關問題