user1437801
user1437801

Reputation: 221

Use global or constant variable in Ruby/Rails?

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(...)

Upvotes: 20

Views: 4732

Answers (3)

Damien
Damien

Reputation: 27463

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

Upvotes: 45

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

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(...)

Upvotes: 9

Dave Newton
Dave Newton

Reputation: 160170

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

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

Upvotes: 4

Related Questions