Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter gem best practice - controller vs. initializer

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?

like image 401
brad Avatar asked Aug 17 '26 03:08

brad


2 Answers

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.

like image 171
Gray Avatar answered Aug 18 '26 16:08

Gray


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
like image 22
Robbo Avatar answered Aug 18 '26 16:08

Robbo