2016-02-11 22 views
0

我的web應用程序處理來自第三方API的webhook,當我收到它們時,我需要用200 OK代碼進行響應。在進行some_api_webhook方法的實際處理之前,我需要檢查幾個條件,如果其中任何一個失敗 - 我不能再進一步處理。在some_api_webhook方法的頂部調用render方法可以嗎?有人告訴我,render應在方法的底部只有放在...可以在頂部調用渲染方法嗎?

我原來的方法:

def some_api_webhook 
    unless condition_a 
    render nothing: true, status: :ok, content_type: "text/html" 
    return 
    end 

    unless condition_b 
    render nothing: true, status: :ok, content_type: "text/html" 
    return 
    end 

    unless condition_c 
    render nothing: true, status: :ok, content_type: "text/html" 
    return 
    end 

# main logic is below 
# ... 
# ... 

end 

重寫的版本,我喜歡更多的是因爲它沒有重複調用render

def some_api_webhook 
    render nothing: true, status: :ok, content_type: "text/html" 
    return unless condition_a 
    return unless condition_b 
    return unless condition_c 

# main logic is below 
# ... 
# ... 

end 
+1

可以稱之爲任何你想要的位置 – Drew

+0

爲什麼你想把渲染放在頂部? – osman

+0

osman,因爲如果我把它放在底部,那麼如果上面的一些'return'語句被觸發,它將不會被調用。 – yaru

回答

2

有趣的我總是認爲渲染將從動作返回並且其下的任何東西都不會被處理。剛做了一個快速測試,結果證明這是錯誤的。在下面的代碼中,put語句仍然被執行。

def index  
    render 'index' 
    puts "Got here!" 
end 

所以在這方面,不要緊,你把渲染,除非渲染是有條件的而你的情況似乎並不如此。