How do I create a singleton global object in rails?
If you want only one instance in your whole application, use a singleton, otherwise use a class variable.
To use a singleton, include the Singleton mixin.
require 'singleton'
class Pubnub
include Singleton
attr_writer :publish_key, :subscribe_key, :secret_key, :ssl_on
def publish
#...
end
end
and then use it like this:
require 'pubnub'
class Message < ActiveRecord::Base
Pubnub.instance.publish_key = 'xyz'
Pubnub.instance.subscribe_key = 'xyz'
Pubnub.instance.secret_key = 'xyz'
Pubnub.instance.ssl_on = 'xyz'
def self.send_new_message_client(message)
message = { 'some_data' => message }
info = Pubnub.instance.publish({
'channel' => 'testing',
'message' => message
})
puts(info)
end
end
You could also make it a class variable, to link it more tightly to a specific model:
require 'pubnub'
class Message < ActiveRecord::Base
@@pubnub_obj = Pubnub.new('xyz', 'xyz', 'xyz', 'xyz')
def self.send_new_message_client(message)
message = { 'some_data' => message }
info = @@pubnub_obj.publish({
'channel' => 'testing',
'message' => message
})
puts(info)
end
end
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.
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
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).
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.
Hope it helps!