Max Rose-Collins
Max Rose-Collins

Reputation: 1924

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?

Upvotes: 2

Views: 398

Answers (2)

KappaNossi
KappaNossi

Reputation: 2716

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

Upvotes: 1

falsetru
falsetru

Reputation: 369134

Using each, the code overwrite username and finally you get the last Twitter::Client object and the return value of the block is not saved.

Use Enumerable#map instead.

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

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

Upvotes: 1

Related Questions