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

use*_*801 19 ruby ruby-on-rails

假设我们有与memcache或redis的连接...哪种风格是首选,为什么?

MEMCACHE = Memcache.new(...)
REDIS = Redis.new(...)
Run Code Online (Sandbox Code Playgroud)

要么

$memcache = Memcache.new(...)
$redis = Redis.new(...)
Run Code Online (Sandbox Code Playgroud)

Dam*_*ien 41

您可能想在此处使用Redis.current更多信息

例如,在初始化程序中:

Redis.current = Redis.new(host: 'localhost', port: 6379)
Run Code Online (Sandbox Code Playgroud)

然后在你的其他课程中:

def stars
  redis.smembers("stars")
end

private

def redis
  Redis.current
end
Run Code Online (Sandbox Code Playgroud)


Tod*_*obs 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(...)
Run Code Online (Sandbox Code Playgroud)


Dav*_*ton 4

IMO 是一个“常数”,因为它传达出它应该是......常数。

全局变量并不意味着它们不应该被改变。

  • 是的。另一个需要考虑的解决方案可能是扩展类以包含诸如“Memcache.connection”和“Redis.connection”之类的内容(有点像“ActiveRecord::Base.connection”),尽管使用这些代码编写代码可能会有点冗长如果它们被大量使用,但这样“常数”就附加到它们的起源上。 (2认同)