开发者

Ruby unless && statement

开发者 https://www.devze.com 2023-04-10 16:14 出处:网络
I have the following in my application_controller.rb def layout unless request.subdomain.empty? && current_user.nil?

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 statemen开发者_如何学JAVAt. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消