簡體   English   中英

在Ruby / Rails中使用全局變量或常量變量?

[英]Use global or constant variable in Ruby/Rails?

假設我們有與memcache或redis的連接...哪種風格是首選,為什么?

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

要么

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

您可能希望在此處使用Redis.current更多信息

例如,在初始化程序中:

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

然后在你的其他課程中:

def stars
  redis.smembers("stars")
end

private

def redis
  Redis.current
end

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

# 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(...)

IMO是一個“常數”,因為它傳達它應該是......不變的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM