如何在 rails 中创建单例全局对象? [英] How do I create a singleton global object in rails?
问题描述
我有一个对象,我想创建一次并在我的模型之一中访问它.我把他放在哪里?恐怕如果我把他放在模型类文件中,每次我创建该模型的新实例时,他都会被创建.我只希望这个对象在启动时创建一次.这是对象:
I have an object that I want created once and accessible in one of my models. Where do I put him? I'm afraid if I put him in the model class file he'll get created every time I make a new instance of that model. I only want this object created once at start up. Here's the object:
require 'pubnub'
publish_key = 'fdasfs'
subscribe_key = 'sdfsdsf'
secret_key = 'fsdfsd'
ssl_on = false
pubnub_obj = Pubnub.new(publish_key,
subscribe_key,
secret_key,
ssl_on)
我在模型中是这样使用他的:
I use him like this in the model:
class Message < ActiveRecord::Base
def self.send_new_message_client(message)
message = { 'some_data' => message }
info = pubnub_obj.publish({
'channel' => 'testing',
'message' => message
})
puts(info)
end
end
推荐答案
在 Rails 中,每个请求都会重新创建对象.如果这是某种服务,它应该是请求范围内的单例.
In Rails, objects are recreated on each request. If this is some kind of service, it should be a singleton in the scope of a request.
应使用 ruby 单例 mixin 创建单例对象:
Singleton objects should be created with the ruby singleton mixin:
require 'singleton'
class Pubnub
include Singleton
def initialize(publish_key, subscribe_key, secret_key, ssl_on)
# ...
end
def publish
# ...
end
end
然后你可以用instance
方法调用它:
Then you can call it with the instance
method:
Pubnub.instance.publish
这样你就可以确保这个对象实际上是一个单例(只存在一个实例).
This way you make sure that this object will actually be a singleton (only one instance will exist).
您可以将它安全地放在 models
目录中,尽管我通常更喜欢 lib
目录,或者可能会为服务创建一个新目录.视情况而定.
You can place it safely in the models
directory, though I often prefer the lib
directory or maybe create a new directory for services. It depends on the situation.
希望有帮助!
这篇关于如何在 rails 中创建单例全局对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!