Alexandre
Alexandre

Reputation: 5135

How to DRY this snippet of Ruby code?

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

Upvotes: 0

Views: 286

Answers (4)

wacko
wacko

Reputation: 3424

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

#present? will handle nil and empty strings

Upvotes: 0

Justin Gallagher
Justin Gallagher

Reputation: 3232

How about:

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

Upvotes: 0

jamuraa
jamuraa

Reputation: 3419

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

Upvotes: 3

Lou Zell
Lou Zell

Reputation: 5597

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.

Upvotes: 4

Related Questions