[英]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.