3

I have a registered app on Twitter and am able to post to my twitter feed. However, I can only get it to work when I put the initializer in my controller's create action.

        client = Twitter::REST::Client.new do |config|
          config.consumer_key = ''
          config.consumer_secret = ''
          config.oauth_token = ''
          config.oauth_token_secret = ''
        end

        client.update("Hello World!")

I got to this point by following the advice in this post: Twitter integration rails 4 app

How do I make this work by having it read a file in my config/initializers / what would the best practice be?

Community
  • 1
  • 1
brad
  • 1,675
  • 2
  • 16
  • 23

2 Answers2

4

So you have a few options. One is to assign the twitter client to a global variable in an initializer:

# config/initializers/twitter.rb
$twitter = Twitter::REST::Client.new do |config|
  # ... 
end

Then use the $twitter global variable elsewhere. I tend to dislike using global variables as it pollutes the global namespace. My alternative is to define class attributes on the relevant class. You could for example define it on ApplicationController, although I'd recommend creating a separate class to handle more complex cases. Using the ApplicationController example, this is what it would look like:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  class << self
    attr_accessor :twitter
  end
end

# config/initializers/twitter.rb
ApplicationController.twitter = Twitter::REST::Client.new do |config|
  # ... 
end

But again, i'd recommend to have a separate class instead of using application controller, if you are going to use this method.

Gray
  • 677
  • 5
  • 14
  • Thank you for responding. I'm slightly confused still. You didn't like the first or second option you proposed. Is there a better one, or is it a lesser than two evils solution? Thanks again! – brad Jan 21 '14 at 23:48
  • @brad the first solution will work just fine. Functionally they both are the same, it's just up to preference really. – Gray Jan 22 '14 at 21:19
3

I would potentially just do the following:

# app/controllers/application_controller.rb

def twitter_client

    Twitter::REST::Client.new do |config|
      config.consumer_key        = ENV["TWITTER_CONSUMER_KEY"]
      config.consumer_secret     = ENV["TWITTER_CONSUMER_SECRET"]
      config.access_token        = ENV["TWITTER_ACCESS_TOKEN"]
      config.access_token_secret = ENV["TWITTER_ACCESS_SECRET"]
    end

end

Then in any of your other controllers or views you should be able to use the twitter_client method.

For example here's a tweet controller where the index action searches for tweets containing "Foo" and takes three of them:

# app/controllers/tweets_controller.rb

def index

    @tweets = twitter_client.search("Foo").take(3)

end
Robbo
  • 1,292
  • 2
  • 18
  • 41