Search code examples
ruby-on-railsconfigtwitter-gem

Putting the Rails Twitter Client initializer in an Initializer


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

Solution

  • 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()