2012-06-05 32 views
16

假設我們與memcache或redis有連接......哪種風格更受歡迎,爲什麼?在Ruby/Rails中使用全局或常量變量?

MEMCACHE = Memcache.new(...) 
REDIS = Redis.new(...) 

OR

$memcache = Memcache.new(...) 
$redis = Redis.new(...) 
+0

我覺得這會更適合[CodeReview.SE]。 – 2012-06-05 16:10:52

回答

3

IMO 「恆定」,因爲它傳達的是它應該是...不變。

全局並不意味着它們不應該發生變異。

+2

是的。要考慮的另一個解決方案可能是擴展類以包含諸如「Memcache.connection」和「Redis.connection」之類的東西(有點像「ActiveRecord :: Base.connection」),儘管它可能有點冗長如果它們被大量使用,那麼這些「常量」就會附在它們的起源上。 – Casper

+0

@Casper也許更好的主意,是的。 –

9

它們不是等價的構造。根據您的應用程序,它們可能可以互換,也可能不可互換,但它們在語義上是不同的。

# MEMCACHE is a constant, subject to scoping constraints. 
MEMCACHE = Memcache.new(...) 

# $memcache is a global variable: declare it anywhere; use it anywhere. 
$memcache = Memcache.new(...) 
+1

+1的額外信息 - 好點。 –

36

您可能需要使用Redis.current更多信息here

例如,在一個初始化:

Redis.current = Redis.new(host: 'localhost', port: 6379) 

,然後在其他類:

def stars 
    redis.smembers("stars") 
end 

private 

def redis 
    Redis.current 
end 
+0

「不要引入全局變量」的好解決方案。 rubocop寶石的錯誤。 – leo