2015-06-17 22 views
1

的鏈條如何使清潔這樣的代碼:清理依賴電話

def some_public_method(arg) 
    var1 = private_method(arg) 
    var2 = private_method1(var1) if var1 
    var3 = private_method2(var2) if var2 
    var4 = private_method3(var3) if var3 
    private_method4(var4) if var4 
end 

UPDATE:對不起,忘了改方法的名稱

+1

這是值得檢查:[重構與單子紅寶石](https://www.youtube.com/watch?v= J1jYlPtkrqQ) – dax

回答

1

這是你能做到這一點的方法之一。

代碼

def some_public_method(private_methods, arg) 
    private_methods.reduce(arg) { |x,m| x && send(m, x) } 
end 

private 

def pm1(arg); arg+1; end 
def pm2(arg); arg+2; end 
def pm3(arg); arg+3; end 

實例

private_methods = [:pm1, :pm2, :pm3] 

some_public_method(private_methods, 0) #=> 6 

def pm2(arg); nil; end 
some_public_method(private_methods, 0) #=> nil 
+0

好吧,我明白了。謝謝。 – zuba