2016-10-07 31 views
0

我使用下面的λ,從READMEResque::Mailer的(https://github.com/zapnap/resque_mailer)聚集:這個lambda如何重寫一個guard子句?

 
    Resque::Mailer.error_handler = lambda { |mailer, _message, error, action, args| 
    # Necessary to re-enqueue jobs that receive the SIGTERM signal 
    if error.is_a?(Resque::TermException) 
     Resque.enqueue(mailer, action, *args) 
    else 
     raise error 
    end 
    } 

不幸的是,代碼庫啓用rubocop,埋怨if..else性質的方法,與錯誤:Use a guard clause instead of wrapping the code inside a conditional expression

我試着在這裏設置了一個unless,但是到目前爲止,不管我設置它的順序如何,raise error都會被執行。在這裏使用警衛條款的正確方法是什麼?

也就是說,我問這個的原因是,下面的例子似乎表明,如果我用unless做了明顯的事情,錯誤總是會被提升。我理解這個錯誤嗎?

 
Development [10] (main)> class Foo 
Development [10] (main)* def bar 
Development [10] (main)*  puts "Outside unless getting exec" unless 1 == 2 
Development [10] (main)*  puts "After unless getting exec" 
Development [10] (main)* end 
Development [10] (main)* end 
:bar 
Development [11] (main)> Foo.new.bar 
Outside unless getting exec 
After unless getting exec 
nil 

回答

1

轉化條件爲unless應該工作,並滿足rubocop

Resque::Mailer.error_handler = lambda { |mailer, _message, error, action, args| 
    # Necessary to re-enqueue jobs that receive the SIGTERM signal 
    raise error unless error.is_a?(Resque::TermException) 
    Resque.enqueue(mailer, action, *args) 
    } 
+0

我曾真的試圖執行一些[例如碼(http://pastebin.com/aG7Hxd8f)這似乎表明如果我這樣做,錯誤總會被提出。你能澄清嗎? –

+0

這不完全正確 - 只有在Resque :: TermException時纔會引發錯誤。 – eugen

+0

好的,更新了我的問題 - 你能解釋爲什麼'puts'表現出不同的表現嗎? –