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