繁体   English   中英

如何干燥这个Ruby代码片段?

[英]How to DRY this snippet of Ruby code?

这困扰着我。 它看起来不太干。 有什么更好的实施方案? 顺便说一句,当找不到记录时,这个ActiveRecord查找器为什么不会引发异常,而.find会引发异常?

  def current_account
    return @account if @account
    unless current_subdomain.blank?
      @account = Account.find_by_host(current_subdomain)
    else
      @account = nil
    end
    @account
  end
def current_account  
  @account ||= current_subdomain && Account.find_by_host(current_subdomain)
end

如果未找到记录,则动态find_by方法返回nil, find_by_all返回空数组。

我会这样编码

def current_account
  @account ||= current_subdomain.blank? ? nil : Account.find_by_host(current_subdomain)
end

至于异常,find_by动态方法返回nil而不是抛出异常。 如果您想要一个异常,可以将find:conditions

def current_account
  @account ||= current_subdomain.blank? ? nil : Account.find(:first, :conditions => {:host  => current_subdomain})
end

怎么样:

def current_account
  @account ||= Account.find_by_host(current_subdomain) unless current_subdomain.blank?
end
def current_account  
  @account ||= current_subdomain.present? && Account.find_by_host(current_subdomain)
end

#present? 将处理nil和空字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM