1
votes

I'm having trouble using omniauth & twitter gem to generate tweets.

I have been using this tutorial http://blog.assimov.net/post/2358661274/twitter-integration-with-omniauth-and-devise-on-rails-3

and I can log in using twitter, generate authentications but I cannot update tweets.

current_user.twitter.update("My Rails 3 App with Omniauth, Devise and Twitter")

This line complains about the method update.

What confuses me about the tutorial above is that at the beginning they generate a migration to store the secret in authentications, but at no point later in the tutorial is any mention of changing any code to write the secret to the database.

My understanding is that the secret is obtained from the omniauth hash that is stored in the session cookie. What am I missing here?

def hash_from_omniauth(omniauth)
  {
      :provider => omniauth['provider'],
      :uid => omniauth['uid'],
      :token => (omniauth['credentials']['token'] rescue nil),
      :secret => (omniauth['credentials']['secret'] rescue nil)
  }
end

So everything seems to be working apart from creating the Twitter Client hence not having the update method available?

current_user.twitter.update("first tweet")

The twitter method here should be creating the Twitter Client

  def twitter
debugger
unless @twitter_user
  provider = self.authentications.find_by_provider('twitter')
  @twitter_user = Twitter::Client.new(:oauth_token => provider.token, :oauth_token_secret => provider.secret )rescue nil
end
@twitter_user

end

I'm sorry I'm not great at explaining the problem. Any help greatly appreciated. Thanks L

1
Are you using the twitter gem for anything else? - mnelson

1 Answers

2
votes

If you only need to post to twitter, it might just be easier to forgo the twitter gem completely. The consumer / access token generation requires the app id and secret as well as the user's access and secret tokens. I found this to be easy enough to implement that I thought the overhead of the twitter gem wasn't necessary.

module User::Social

  def self.included(base)
    base.instance_eval do
      include Rails.application.routes.url_helpers
    end
  end


  def promote_activity(type, profile)
    url = short_profile_url(profile, :host => Conf.domain)
    tw_client.request(:post, "http://api.twitter.com/1/statuses/update.json", :status => I18n.translate("tweets.#{type}", :profile => profile.to_s, :url => url))
  end

  def tw_client
    @tw_client ||= begin
      consumer = OAuth::Consumer.new(Conf.tw_app_id, Conf.tw_secret, :site => 'http://api.twitter.com')
      OAuth::AccessToken.from_hash(consumer, {:oauth_token => self.access_token, :oauth_token_secret => self.secret_token})
    end
  end
end


class User < AR::Base
  include User::Social
end