简体   繁体   中英

What is a good place to initialize API clients in rails?

To give an example, these two gems https://github.com/philnash/bitly and https://github.com/nfo/gmail_xoauth require something like

client = Bitly.client

And

imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)

Am I suppose to initialize these clients every time I use them? Eg in every function I need to use methods from those clients?

EDIT: still not sure how to go about initizalizing a library like this

require 'mixpanel-ruby'
tracker = Mixpanel::Tracker.new(PROJECT_TOKEN)
tracker.track(user_id, 'Sent Message')

创建ocnfig / initializers / bitly.rb

config.bitly_client = Bitly.client

You can also write this in any of the Environment files under config/environments/ also for environment specific solution or even in config/environment.rb also where it applies to all environments as an option to config/initializers/any_file_name.rb.

Make sure the Class name must be appropriate in case of config/initializers/any_file_name.rb

If the client just needs configuration for your own tokens and such. I would setup a client in a app/config/initializers/goodreads.rb all files in the initialize folder will get loaded into your environment.

If you are setting up a unique client per a User's own token you may want to make a helper method in a concern.

once you create your client save it to a variable and use throughout your application as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM