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