[英]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.