需要帮助重构并加快if语句的查看速度

时间:2013-04-21 13:14:06

标签: ruby-on-rails optimization refactoring dry

我的助手中有以下Ruby on Rails代码。当我在页面上有很多链接时,我的视图加载缓慢。

任何人都可以向我展示一个可以干并加速的重构版本吗?

https://gist.github.com/anonymous/2afe1956e7565731ff20

module ApplicationHelper

  def link_to_doc(document)
    if document.document_type.downcase == "image"
      link_to "#{document.name}", "#{document.url}", class: "sublime"
    elsif document.document_type.downcase == "video"
      sublime_video_link_to(document)
    elsif document.url && document.url.length > 0
      link_to "#{document.name}", "#{document.url}", download: "#{document.name.parameterize}"
    elsif document.admin_url && document.admin_url.length > 0
     content_tag :a, href: document.admin_url do
       link_to "#{document.name}", document.admin_url
     end
    else
      link_to "#{document.name}", document_url(document)
    end
  end

  def btn_link_to_doc(document)
    if document.document_type.downcase == "image"
      link_to "View #{ document.document_type.downcase }", "#{document.url}", class: "document-link btn sublime"
    elsif document.document_type.downcase == "video"
      sublime_video_btn_link_to(document)
    elsif document.url && document.url.length > 0
      link_to "Download #{ document.document_type.downcase }", "#{document.url}", download: "#{document.name.parameterize}", class: "document-link btn"
    elsif document.admin_url && document.admin_url.length > 0
     content_tag :a, href: document.admin_url do
       link_to "View", document.admin_url, class: "document-link btn"
     end
    else
      link_to "View", document_url(document), class: "document-link btn"
    end
  end  


private


  def sublime_video_btn_link_to(document)
     tag=[]
      tag<<link_to("View #{ document.document_type.downcase}", "#video#{document.id}", class: "document-link btn sublime", data: { settings: 'close-button-visibility:visible' })  
      tag<<  content_tag(:video,{ id: "video#{document.id}", style: "display:none;", width:'480', height:'270', preload: true }) do
              content_tag(:source, nil,{src: document.url}) 
             end
      tag.join.html_safe
  end

  def sublime_video_link_to(document)
     tag=[]
      tag<<link_to("#{document.name}", "#video#{document.id}", class: "sublime", data: { settings: 'close-button-visibility:visible' })  
      tag<<  content_tag(:video,{ id: "video#{document.id}", style: "display:none;", width:'480', height:'270', preload: true }) do
              content_tag(:source, nil,{src: document.url}) 
             end
      tag.join.html_safe
  end
end

1 个答案:

答案 0 :(得分:2)

而不是这些双重检查

    document.admin_url && document.admin_url.length > 0

你可以使用

   document.url.to_s.blank?

它将检查nil和空字符串