20

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(...)
user1437801
  • 221
  • 2
  • 6

3 Answers3

45

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
Damien
  • 26,933
  • 7
  • 39
  • 40
9

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(...)
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
4

IMO a "constant", because it communicates that it's supposed to be... constant.

Globals don't imply they shouldn't be mutated.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 2
    Yes. Another solution to consider might be to extend the classes to include something like `Memcache.connection` and `Redis.connection`, (a bit like `ActiveRecord::Base.connection`) although it might get a bit verbose to code with those if they are used a lot, but this way the "constants" are attached to their origins. – Casper Jun 05 '12 at 16:21
  • @Casper Probably even better idea, yep. – Dave Newton Jun 05 '12 at 16:27