2013-02-16 67 views
-1

這可行,但它看起來不太合適。想知道我錯過了什麼,或者如果我能以某種方式簡化它?當塊需要變量時將塊傳遞給方法

摘掉$redis的東西。

def redis_with_connection(&block) 
    $redis.with_connection { |conn| yield(conn) } 
    # perhaps do other stuff like begin/rescue, etc. 
end 

於是我可以在我的應用程序

redis_with_connection do |conn| # is this conn variable necessary here? 
    conn.set # do stuff with the connection 
end 

回答

2

你並不需要產生變量如果你只是路過塊到.with_connection方法調用此。相反,您只需將該塊作爲參數傳遞即可:

def redis_with_connection(&block) 
    $redis.with_connection(&block) 
    # etc ... 
end