How to DRY this snippet of Ruby code?
-
05-07-2019 - |
Question
This is bothering me. It doesn't look too DRY. What would be a better implementation? As an aside, how come this ActiveRecord finder doesn't throw an exception when record is not found, but .find does?
def current_account
return @account if @account
unless current_subdomain.blank?
@account = Account.find_by_host(current_subdomain)
else
@account = nil
end
@account
end
Solution
I would code this like
def current_account
@account ||= current_subdomain.blank? ? nil : Account.find_by_host(current_subdomain)
end
As for the exceptions, find_by dynamic methods return nil
instead of throwing an exception. If you want an exception, use the find
with :conditions
:
def current_account
@account ||= current_subdomain.blank? ? nil : Account.find(:first, :conditions => {:host => current_subdomain})
end
OTHER TIPS
def current_account
@account ||= current_subdomain && Account.find_by_host(current_subdomain)
end
If a record isn't found, the dynamic find_by
methods return nil, find_by_all
returns an empty array.
How about:
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?
will handle nil
and empty strings
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow