Configuring Twitter Gem with Ruby on Rails - ruby-on-rails

I am trying to do a simple rails app that will search Twitter. I am using the Twitter gem (http://sferik.github.io/twitter/). I created a twitter_credentials.rb in the initializer folder with following code:
require 'twitter'
Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
end
My view looks like this:
<% Twitter.search("to:justinbieber marry me",
:result_type => "recent").take(3).each do |tweet| %>
<%= tweet.text %>
<% end %>
However, whenever I try to call any method from the docs, I get an error "undefined method method name for Twitter:Module". I've also tried moving that block into the appropriate controller but I receive the same error. Any help would be really appreciated..

I faced with same issue. But I have installed two gems https://github.com/sferik/twitter and https://github.com/twitter/twitter-text-rb, they both have 'Twitter' as main module and when I call Twitter, I reached second instead first...

Related

Rails app with Twitter API: undefined method `user' for nil:NilClass

I'm trying to integrate my app with twitter API.
here are my steps:
1: installed the twitter gem: gem 'twitter
2:grabbed this code from the twitter gem documentation and placed it inside my controller. I also tried placing the code in a helper.
require 'twitter'
#client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["CONSUMER_KEY"]
config.consumer_secret = ENV["CONSUMER_SECRET"]
config.access_token = ENV["ACCESS_TOKEN"]
config.access_token_secret = ENV["ACCESS_SECRET"]
end
3) registered my app with twitter and got the consumer_key (AKA: API key), consumer_secret (AKA:API secret), access_token, and access_token_secret.
I used a config/application.yml to store access tokens. is that correct way of doing it? I hope so.
4) in views, I have <%= #client.user.username %>.
I'm doing this in development (localhost3000). my callback url is http://127.0.0.1/
I also tried to organize my code as this answer suggests to no avail.
I'm using Rails 4.0.2
I tested the code in the console and is working perfectly. I tried several queries including the one shown above: <%= #client.user.username %> and they are all working.
but when I run my code in development i get this error:
undefined method `user'` for nil:NilClass.
I understand what the error means. but how is it possible that #client is nil? when I run it in the console, it is not nil. Did I forget something? I would appreciate any suggestions. Please let me know if you would like me to provide more info/code. Thanks.
EDIT: Also, tried to move the above code that start with #client to a config/initializers/twitter.rb. Getting same error message.
This may be because your controller code is trying to access CONSUMER_KEY etc. from environment variable but you have not set it in development mode.
You can use rails_config gem and let it create the settings.yml file for you in config/ with appropriate configurations.
] Now, store you twitter details in it as follows:
twitter:
CONSUMER_KEY: 'your_consumer_key_here'
CONSUMER_SECRET: 'your_consumer_secret_here'
ACCESS_TOKEN: 'your_access_token_here'
ACCESS_SECRET:'your_access_secret_here'
Then, modify your controller code to use those values as follows:
account = Settings['twitter']
#client = Twitter::REST::Client.new do |config|
config.consumer_key = account["CONSUMER_KEY"]
config.consumer_secret = account["CONSUMER_SECRET"]
config.access_token = account["ACCESS_TOKEN"]
config.access_token_secret = account["ACCESS_SECRET"]
end
You can add settings.yml to .gitignore so that the file is not commited by git.
Or, you can use the approach described Here.
You can read this if you are thinking of setting ENV variables in development.
I think your keys are not getting loaded properly
your config/settings.yml should look like this
development:
twitter:
CONSUMER_KEY: 'your_consumer_key_here'
CONSUMER_SECRET: 'your_consumer_secret_here'
ACCESS_TOKEN: 'your_access_token_here'
ACCESS_SECRET:'your_access_secret_here'
make this file as per your environments
Then Load this as
def get_twitter_client
oauth_config = YAML::load(File.open("#{Rails.root}/config/settings.yml"))
#client = Twitter::REST::Client.new do |config|
config.consumer_key = oauth_config[Rails.env]['twitter']["CONSUMER_KEY"]
config.consumer_secret = oauth_config[Rails.env]['twitter']["CONSUMER_SECRET"]
config.access_token = oauth_config[Rails.env]['twitter']["ACCESS_TOKEN"]
config.access_token_secret = oauth_config[Rails.env]['twitter']["ACCESS_SECRET"]
end
end
Also if you look at Twitter gem #client has method user(user show API) which accepts user_id or twitter_username/handle/screen_name
I tried both solutions outlined here by #Pramod Shinde and #Peeyush, but none of them seemed to work for me. Here is how I solved the problem.
What I needed to do is to wrap a method action around the following code which I had inside my controller. Like this:
def tweets
#client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["CONSUMER_KEY"]
config.consumer_secret = ENV["CONSUMER_SECRET"]
config.access_token = ENV["ACCESS_TOKEN"]
config.access_token_secret = ENV["ACCESS_SECRET"]
end
end
I created a new file, config/application.yml to store my twitter API credentials, and added the file to .gitignore to avoid it being commited to github. The above code uses ENV[] to access the credentials stored in config/application.yml.
config/application.yml:
CONSUMER_KEY: "1234"
CONSUMER_SECRET: "1234"
ACCESS_TOKEN: "1234"
ACCESS_SECRET: "1234"
This is a YAML file. So beware of the indentation.
Then inside my routes.rb, I created a route that maps to the above action:
get "/tweets", to: "posts#tweets"
Obviously, if you wanted to post tweets instead of fetching them, you'd have to create a POST route. You may also consider moving the above action to it's own TweetsController. Or encapsulate it in it's own class.
To complete the convention, I created a view file which maps to the tweets action:
tweets.html.erb
The reason why I was getting this error message:
undefined method `user' for nil:NilClass
is because I didn't have a route, controller action, and a view file that map to each.
Up until this point, everything is working fine when in development.
when I pushed the app to heroku, I got the following error:
ActionView::Template::Error (Unable to verify your credentials):
Solution: install gem 'figaro' (actually this gem creates for you config/application.yml file and automatically appends it to .gitignore.
To solve the heroku error, all you have to do is run: rake figaro:heroku. See this tutorial about using the figaro gem to keep the environment variables private

Can't initialize Twitter Gem For Rails

I've been trying to get the Twitter Gem running. I followed the documentation and placed
client = Twitter::REST::Client.new do |config|
config.consumer_key = "YOUR_CONSUMER_KEY"
config.consumer_secret = "YOUR_CONSUMER_SECRET"
config.access_token = "YOUR_ACCESS_TOKEN"
config.access_token_secret = "YOUR_ACCESS_SECRET"
end
I placed it in a custom initializer file called Twitter.rb
When I try to run rails console it gives me this error " uninitialized constant Twitter::REST (NameError)"
This error was reported here
The solution is to use Twitter::Client.new (no ::REST)
I faced with same issue. But I have installed two gems https://github.com/sferik/twitter and https://github.com/twitter/twitter-text-rb, they both have 'Twitter' as main module and when I call Twitter, I reached second instead first...
Twitter::Client.new - not working to.
add require 'twitter' on the top of your file

Rails - Adding a command line script to my app

I don't like asking noobie questions but I've spent more time than I care to admit googling and trying to figure out this simple process. I'm trying to use the twitter gem to post tweets in my app's views.
I have this script that works when I run it on the command line, but I don't know how to access the data on my views. I have the gem installed. I tried adding this code to my controller but it still doesn't let me call it in the view.
require 'rubygems'
require 'twitter'
client = Twitter::REST::Client.new do |config|
config.consumer_key = "(redacted)"
config.consumer_secret = "(redacted)"
config.access_token = "(redacted)"
config.access_token_secret = "(redacted)"
end
client.search("help", :result_type => "recent").take(3).each do |tweet|
puts tweet.text
end
If anyone can point me in the right direction, that would be great.
Well, I'll post some (untested) code that might help set you in the right direction. It's not the best way to do it, as it's not very flexible, but it should do what your example does. Make sure add the Twitter gem to your Gemfile and bundle install. Create a Ruby class called TweetsFromAccount. Saving it in the /lib directory works just fine.
class TweetsFromAccount
def initialize
#client = Twitter::REST::Client.new do |config|
config.consumer_key = "(redacted)"
config.consumer_secret = "(redacted)"
config.access_token = "(redacted)"
config.access_token_secret = "(redacted)"
end
end
def recent_tweets(quantity)
array_of_tweets = []
#client.search("help", :result_type => "recent").take(quantity).each do |tweet|
array_of_tweets << tweet.text
end
end
end
In the controller, create a new TweetsFromAccount object and assign it to an instance variable, #tweets. Create an additional instance variable set the value of #tweets.recent_tweets(3). This should fetch the 3 most recent tweets.
def show
# other stuff
#tweets = TweetsFromAccount.new
#array_of_tweets = #tweets.recent_tweets(3)
end
Then in your view, just iterate over #array_of_tweets.
<ul>
<% #array_of_tweets.each do |tweet| %>
<li><%= tweet %></li>
<% end %>
</ul>

How to implement the search for the twitter APIs in controller as well as in Erb template?

I am new to Ruby on Rails as i want to develop a twitter app with the search option. Using which an user can search for the other users. I am using twitter gem and oauth gem for my project. I Have tried using below given code but its not working though get_client.search("user") it working in Rails Console.
def get_client
Twitter::REST::Client.new do |config|
config.consumer_key = "ABCD"
config.consumer_secret = "XYZ"
config.access_token = "PQRS"
config.access_token_secret = "LMNO"
end
end
def search
query = (param[:search])
get_client.search("query")
end

Tweetstream not connecting?

I'm using a recent version of Tweetstream and can't seem to connect to the twitter streaming API. I'm authenticating through oAuth like so:
require "rubygems"
require "tweetstream"
def index
TweetStream.configure do |config|
config.consumer_key = 'aaa'
config.consumer_secret = 'aaa'
config.oauth_token = '11329872-aaa'
config.oauth_token_secret = 'aaa'
config.auth_method = :oauth
config.parser = :yajl
end
TweetStream::Client.new.track('words') do |status|
puts "streaming"
puts "#{status.text}"
end
end
It eventually times out though with the following:
TweetStream::ReconnectError (Failed to reconnect after 7 tries.)
Any idea what's wrong?
Found the solution to this one was a missing required gem. All I needed to add was:
require 'yajl'
I also noticed that this is only required if you're using oAuth to authenticate with twitter.

Resources