在 Ruby/Rails 中使用全局变量还是常量变量? [英] Use global or constant variable in Ruby/Rails?

查看:48
本文介绍了在 Ruby/Rails 中使用全局变量还是常量变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们与 memcache 或 redis 有连接...更喜欢哪种风格,为什么?

Say we have a connection to memcache or redis... which style is preferred and why?

MEMCACHE = Memcache.new(...)
REDIS = Redis.new(...)

$memcache = Memcache.new(...)
$redis = Redis.new(...)

推荐答案

您可能想要使用 Redis.current 更多信息 这里

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

这篇关于在 Ruby/Rails 中使用全局变量还是常量变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆