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