I am currently using the mixpanel_client gem to access the mixpanel API. I would like to be able to do this开发者_如何学Python in one place:
config = {'api_key' => 'changeme', 'api_secret' => 'changeme'}
client = Mixpanel::Client.new(config)
and then access it anywhere throughout the app. Is there an idiomatic (or framework-matic) way to go about this? It seems like doing this everytime I want to make a request is a waste of resources and not very DRY to boot.
Thanks!
There are a few ways to do it, create an initializer, under initializer folder, so that it will be loaded once after rails is loaded, then
config = {'api_key' => 'changeme', 'api_secret' => 'changeme'}
CLIENT = Mixpanel::Client.new(config)
Then the CLIENT constant will be available anywhere in your app.
Else you can create a class
class MixPanelClient
cattr_accessor: client
def self.client
client ||= begin
config = {'api_key' => 'changeme', 'api_secret' => 'changeme'}
Mixpanel::Client.new(config)
end
end
end
MixPanelClient.client would only create that client once.
精彩评论