Say we have a connection to memcache or redis... which style is preferred and why?
MEMCACHE = Memcache.new(...)
REDIS = Redis.new(...)
OR
$memcache = Memcache.new(...)
$redis = Redis.new(...)
Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program. Instead of using global variables, use local variables in the program.
Although constants look like local variables with capital letters, they have the visibility of global variables: they can be used anywhere in a Ruby program without regard to scope.
Ruby ConstantsConstants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods.
You might want to use Redis.current
More info here
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With