leo*_*nel 23 ruby ruby-on-rails
我在application_controller.rb中有以下内容
def layout
unless request.subdomain.empty? && current_user.nil?
self.class.layout 'admin'
end
end
Run Code Online (Sandbox Code Playgroud)
看来它上面的代码不起作用.但是,当我执行以下操作时,它确实有效.
def layout
unless request.subdomain.empty?
unless current_user.nil?
self.class.layout 'admin'
end
end
end
Run Code Online (Sandbox Code Playgroud)
我想通过删除一个除非声明来简化代码.我怎么能这样做?
Fem*_*ref 63
unless something相当于if !something.在你的情况下,那将是
if !(request.subdomain.empty? && current_user.nil?)
Run Code Online (Sandbox Code Playgroud)
随你怎么便
if (!request.subdomain.empty? && !current_user.nil?)
Run Code Online (Sandbox Code Playgroud)
使用布尔代数(De Morgan规则),您可以将其重写为
if !(request.subdomain.empty? || current_user.nil?)
Run Code Online (Sandbox Code Playgroud)
运用 unless
unless request.subdomain.empty? || current_user.nil?
Run Code Online (Sandbox Code Playgroud)
如果您想布局设置'admin' ,如果子域是不是空的和当前用户不是零:
def layout
if !request.subdomain.empty? && !current_user.nil?
self.class.layout 'admin'
end
end
Run Code Online (Sandbox Code Playgroud)
将逻辑更改为使用if语句和正谓词,它将使代码中的逻辑更容易理解:
def layout
if request.subdomain.present? && current_user
self.class.layout "admin"
end
end
Run Code Online (Sandbox Code Playgroud)
unless除了最琐碎的情况外,最佳做法是避免.
使用:
if (!request.subdomain.empty? && !current_user.nil?)
Run Code Online (Sandbox Code Playgroud)
我从不使用unless任何更复杂的东西(包含或/和),这样的声明太难以理解.