views:

134

answers:

3

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
A: 

How about:

def current_account
  @account ||= Account.find_by_host(current_subdomain) unless current_subdomain.blank?
  @account
end
Justin Gallagher
+5  A: 
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.

Lou Z.
+1, yours is much better than mine.
Mark A. Nicolosi
Alexandre
However this fails if current_subdomain is "". "" evaluates to true in boolean context. Should be `!current_subdomain.blank?`
EmFi
+3  A: 

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
jamuraa