简体   繁体   English

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

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

Say we have a connection to memcache or redis... which style is preferred and why? 假设我们有与memcache或redis的连接...哪种风格是首选,为什么?

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

OR 要么

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

You might want to use Redis.current More info here 您可能希望在此处使用Redis.current更多信息

For example, in an initializer: 例如,在初始化程序中:

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

And then in your other classes: 然后在你的其他课程中:

def stars
  redis.smembers("stars")
end

private

def redis
  Redis.current
end

They are not equivalent constructs. 它们不是等同的结构。 Depending on your application, they may or may not be interchangeable, but they are semantically different. 根据您的应用程序,它们可能是也可能不可互换,但它们在语义上是不同的。

# 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 a "constant", because it communicates that it's supposed to be... constant. IMO是一个“常数”,因为它传达它应该是......不变的。

Globals don't imply they shouldn't be mutated. 全球并不意味着它们不应该发生变异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM