Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
leonel Avatar asked Sep 05 '25 03:09

leonel


2 Answers

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?
like image 54
Femaref Avatar answered Sep 08 '25 22:09

Femaref


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.

like image 26
molf Avatar answered Sep 08 '25 22:09

molf