如何干掉这段Ruby代码?

时间:2009-10-21 16:52:49

标签: ruby-on-rails dry

这困扰着我。它看起来不太干燥。什么是更好的实施?顺便说一句,为什么这个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

4 个答案:

答案 0 :(得分:5)

def current_account  
  @account ||= current_subdomain && Account.find_by_host(current_subdomain)
end

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

答案 1 :(得分:3)

我会像

那样编码
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

答案 2 :(得分:0)

怎么样:

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

答案 3 :(得分:0)

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

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