2014-02-11 1 views
0

다음 코드가 있습니다.이 도우미를 두 가지 방법으로 분해하고 뷰에서 사용하는 방법은 무엇입니까?

def links_in_body(comment_text) 
    # show short part of link 
    regex_url = %r{^(http|https):\/\/|[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?$} 
    comment_text.gsub!(regex_url) { |link| truncate(link, length: 30) } 

    # detect links to site's videos and show title 
    regex = %r{http:\/\/#{request.host_with_port}(\/[\w\/]+)[\.,!\s]?} 
    comment_text.gsub(regex) do |matched| 
    params = Rails.application.routes.recognize_path request.path 

    # 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] == 'videos' && params[:action] == 'show' 
     video = Video.find params[:id] 
     link_to "#{video.title} ".html_safe, video_path(video) 
    # otherwise just return the string without any modifications 
    else 
     matched 
    end 
    end 
end 

나는 코드 약어로 https://github.com/vmg/rinku을 사용하기로 결정했다.

이렇게 나왔다.

def links_in_body(comment_text) 
    # show short part of link 
    Rinku.auto_link(comment_text) do |url| 
    truncate(link, length: 30) 
    end 

    # detect links to site's videos and show title 
    regex = %r{http:\/\/#{request.host_with_port}(\/[\w\/]+)[\.,!\s]?} 
    comment_text.gsub(regex) do |matched| 
    params = Rails.application.routes.recognize_path request.path 

    # 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] == 'videos' && params[:action] == 'show' 
     video = Video.find params[:id] 
     link_to "#{video.title} ".html_safe, video_path(video) 
    # otherwise just return the string without any modifications 
    else 
     matched 
    end 
    end 
end 

"# 사이트의 동영상에 링크 검색 및 제목 표시"후에 코드 부분이 작동하지 않습니다.

전망 : 나에게 두 가지 방법으로이 도우미를 중단하고보기에 그것을 사용하는 방법을

= links_in_body(comment.body).html_safe 

?

답변

0

여기 코드의 작은 조각이 누락되었다고 생각합니다. rinku auto_link 메서드가 반환하는 문자열을 전달해야합니다.

def links_in_body(text) 
    text = auto_link(text) { |url| truncate(link, length: 30) } 
    auto_link_video(text) 
end 

def auto_link_video(text) 
    regex = %r{http:\/\/#{request.host_with_port}(\/[\w\/]+)[\.,!\s]?} 
    text.gsub(regex) do |matched| 
    if controller_name == 'videos' && action_name == 'show' 
     video = Video.find params[:id] 
     link_to "#{video.title} ".html_safe, video_path(video) 
    else 
     matched 
    end 
    end 
end 
0

DRY :

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 
이 청소기의 솔루션이 될 수 있습니다
관련 문제