leonel
leonel

Reputation: 10214

Ruby unless && statement

I have the following in my application_controller.rb

def layout
  unless request.subdomain.empty? && current_user.nil?
    self.class.layout 'admin'
  end
end

It seems the code above it's not working. But when I do the following, it does work.

def layout
  unless request.subdomain.empty?
    unless current_user.nil?
      self.class.layout 'admin'
    end
  end
end

I would like to simplify the code by removing one unless statement. How could I do that?

Upvotes: 29

Views: 18096

Answers (3)

psyho
psyho

Reputation: 7212

Use:

if (!request.subdomain.empty? && !current_user.nil?)

I never use unless with anything that is more complex (contains or/and), it's just too hard to reason about a statement like that.

Upvotes: 6

molf
molf

Reputation: 74935

If you want to set the layout to 'admin' if the subdomain is not empty and the current user is not nil:

def layout
  if !request.subdomain.empty? && !current_user.nil?
    self.class.layout 'admin'
  end
end

Change your logic to use if statements and positive predicates, it will make the logic in your code much easier to understand:

def layout
  if request.subdomain.present? && current_user
    self.class.layout "admin"
  end
end

Best practice is to avoid unless except in the most trivial cases.

Upvotes: 8

Femaref
Femaref

Reputation: 61437

unless something is equivalent to if !something. In your case, that would be

if !(request.subdomain.empty? && current_user.nil?)

However, you want

if (!request.subdomain.empty? && !current_user.nil?)

Using boolean algebra (De Morgan rule), you can rewrite that to

if !(request.subdomain.empty? || current_user.nil?)

Using unless

unless request.subdomain.empty? || current_user.nil?

Upvotes: 79

Related Questions