Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use global or constant variable in Ruby/Rails?

Tags:

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(...)
like image 533
user1437801 Avatar asked Jun 05 '12 16:06

user1437801


People also ask

Is it better to use global variables?

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.

Are constants global in Ruby?

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.

How do you define a constant variable in Ruby?

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.


1 Answers

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
like image 140
Damien Avatar answered Sep 26 '22 23:09

Damien