2011-10-05 119 views
18

我已經在我的application_controller.rb紅寶石除非&&聲明

def layout 
    unless request.subdomain.empty? && current_user.nil? 
    self.class.layout 'admin' 
    end 
end 

以下似乎它上面的代碼不工作。但是當我做下面的事時,它確實有效。

def layout 
    unless request.subdomain.empty? 
    unless current_user.nil? 
     self.class.layout 'admin' 
    end 
    end 
end 

我想通過刪除一個除非聲明來簡化代碼。我怎麼能這樣做?

回答

55

unless something相當於if !something。在你的情況,這將是

if !(request.subdomain.empty? && current_user.nil?) 

但是,你要

if (!request.subdomain.empty? && !current_user.nil?) 

中使用布爾代數(德摩根規則),你可以重寫,要

if !(request.subdomain.empty? || current_user.nil?) 

使用unless

unless request.subdomain.empty? || current_user.nil? 
+0

你是男人。很好的回答... – jaydel

8

如果您想佈局設置爲'admin'如果子域是當前用戶零:

def layout 
    if !request.subdomain.empty? && !current_user.nil? 
    self.class.layout 'admin' 
    end 
end 

更改您的邏輯來使用if語句和積極的謂詞,它會使您的代碼中的邏輯更容易理解:

def layout 
    if request.subdomain.present? && current_user 
    self.class.layout "admin" 
    end 
end 

最佳做法是避免unless除最微不足道的情況外。

4

用途:

if (!request.subdomain.empty? && !current_user.nil?) 

我從來沒有使用unless有任何比較複雜(包含或/和),它太硬來思考這樣一個聲明。