简体   繁体   中英

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?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM