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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With