I have an initializer twitter.rb
:
require 'twitter'
client = Twitter::REST::Client.new(
{
:consumer_key => "",
:consumer_secret => "",
:access_token => "",
:access_token_secret=> "",
}
)
Then I want to be able to access this 'client' in other files say, a model called tag.rb
, could I do it just as:
puts client
FYI those credentials should be moved out of your initializer and into environment variables e.g. ENV['TWITTER_ACCESS_TOKEN']
etc..
You have a few options with regard to accessing the client throughout the code.
Store the Twitter client in a global variable. Global variables are generally considered a bad idea. $twitter_client = Twitter::REST::Client.new(...)
Create a singleton class. This probably won't be thread safe.
Use the factory pattern to generate a new client when/where you need it. For example,
In app/services/twitter_api.rb
:
class TwitterAPI
def client
@client ||= Twitter::REST::Client.new do |config|
config.key = ENV['VALUE'] # for each required credential
end
end
end
TwitterAPI.new.client.do_something()