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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With