in Ruby on Rails

Tweet Random Quotes with Ruby

I recently started using Buffer with my Twitter account in the hopes that I would be more active by queuing up my tweets in advance.  One of the great things about Buffer is that it offers suggestions on things you might want to post.  Often times they have quotes in their suggestions and since I am a big fan of quotes I decided to write my own tool to just publish quotes.

I’ve become a big fan of Ruby on Rails lately but I haven’t written many Ruby scripts yet so I decided this would be a good time. I found a great and easy to use API for quotes from I Heart Quotes that will return a random quote to you. It has a variety of options and sources so you can only pull quotes specific to your niche if you want. I use ‘OAuth’ and ‘open-uri’ for the script. Now onto the code!

You can see it is very easy to make a call to I Heart Quote’s API. You then need to read what it returns and store it in a variable. In the update_hash I use .strip to remove white space before and after the quote so that I can include my own ” ” around the actual quote.

You can see in my call to their API I limited the quote to 138 characters max (because I add ” “) & am choosing not to show the link or source of the quote. Be sure to check out their API to see the different options you can use.

Token & secret would be your account’s token & secret. This means if you wanted to do this for multiple accounts you would need them to allow you access to this information using a web app or alternative. If this is all Greek to you and you don’t have access to Twitter’s API check out their Getting Started guide. One key thing is remember to change your app permissions to allow read AND write. By default this is just set to read and seems to be a major problem most people have when starting with the Twitter API.

If you are confused by the prepare_access_token function all it is doing is reaching out to Twitter to get an access_token which will allow you to update a Twitter account’s feed (among other things). Remember that it is important to not give away your API or token secrets so please don’t post them in code that is reachable by others.

You can see this is less than 40 lines of code and hopefully gives you ideas of what else is possible with Twitter’s API and Ruby. The next thing I will be doing with this code is moving it over to a Rails app and setting up a cron job to post quotes at specific times as well as adding #hashtags to the tweets. Hopefully then this will be useful to more than just myself!

Write a Comment


  1. Hello Jesse. I’m interested in contacting you regarding your dotawithme website. I have a proposal for you regarding purchasing your domain name. Please contact me at the email account given.