0

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
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
NNNNNNNNNNDelicious
  • 933
  • 3
  • 7
  • 19

2 Answers2

4

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.

  1. Store the Twitter client in a global variable. Global variables are generally considered a bad idea. $twitter_client = Twitter::REST::Client.new(...)

  2. Create a singleton class. This probably won't be thread safe.

  3. 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()
R Milushev
  • 4,295
  • 3
  • 27
  • 35
Jeriko
  • 6,547
  • 4
  • 28
  • 40
0

I'd recommend not using the word 'client' as you might need others in the future and that can be confusing. But ultimately.. you're so very close.

The client code from the initializer was run, but you can't access it because it's localized. All you need to do is make your client global and then reference the global variable when you need it.

So your initializer becomes:

$twitter_client = Twitter::REST::Client.new(
    {
      :consumer_key       => "",
      :consumer_secret    => "",
      :access_token       => "",
      :access_token_secret=> "",
    }       
 )

And your call to it becomes:

$twitter_client.search("#railsiscool")

PLEASE do yourself a huge favor though and don't overuse globals, they make very little sense in most rails apps and can cause you problems.

trh
  • 7,186
  • 2
  • 29
  • 41