Search code examples
ruby-on-railsrubytwittertwitter-gem

Instantiate multiple twitter accounts with Ruby on Rails twitter gem


I am using sferiks gem https://github.com/sferik/twitter

I want to instantiate multiple accounts from within a loop.

This is what I thought would work...

twitter_accounts.each do |twitter_account|
    username = twitter_account['username']
    token = twitter_account['oauth_token']
    secret = twitter_account['oauth_token_secret']

    username = Twitter::Client.new(
        :oauth_token => token,
        :oauth_token_secret => secret
    )
end

If I was to instantiate multiple accounts without a loop

erik = Twitter::Client.new(
  :oauth_token => "Erik's access token",
  :oauth_token_secret => "Erik's access secret"
)

john = Twitter::Client.new(
  :oauth_token => "John's access token",
  :oauth_token_secret => "John's access secret"
)

then to post using the gem you would do

Thread.new{erik.update("test")}
Thread.new{john.update("test")}

What am I doing wrong?


Solution

  • Is the usage of the username variable just an error in your post? If not, you are overwriting your twitter client instantiation for every account and username will only contain the last one. Use a hash to store them one by one.

    accounts = {}
    twitter_accounts.each do |twitter_account|
        username = twitter_account['username']
        token = twitter_account['oauth_token']
        secret = twitter_account['oauth_token_secret']
    
        accounts[username] = Twitter::Client.new(
            :oauth_token => token,
            :oauth_token_secret => secret
        )
    end
    
    Thread.new{accounts['erik'].update('test')} # post stuff