Quotes can provide inspiration or food for thought. In this entry, I’m examining the use of open-uri and feed-normalizer to get a random quote which could be used as either a thought for the day or a “fortune” replacement.
open-uri is very useful — it provides a “nice” interface to opening and reading uri’s. feed-normalizer provides the ability to have a single interface to both rss and atom feeds. The two make it very easy to get a random quotation. I’m using ThinkExist for the source of the quotes, but you may have other sources which you prefer.
The code is really pretty simple. There is, however, one dependency, the feed-normalizer gem, which you can install via:
1 |
sudo gem install feed-normalizer |
Once it’s installed, you can use the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
require 'rubygems' require 'open-uri' require 'feed-normalizer' class String # the following method is based on: # http://blog.macromates.com/2006/wrapping-text-with-regular-expressions/ def wrap(col = 80) self.gsub(/(.{1,#{col}})(?: +|$\n?)|(.{1,#{col}})/, "\\1\\2\n") end end url = 'http://en.thinkexist.com/rss.asp?special=random' f = FeedNormalizer::FeedNormalizer.parse open(url) number_of_quotes = f.items.length quote = f.items[rand(number_of_quotes)] puts quote.content.wrap puts "-- #{quote.title} (#{quote.urls.first})".wrap |
It opens the feed, and gets the number of quotes returned — in my tests, it’s been five (5), but I don’t want to hardcode a number, hence the variable. From this set of quotes, I’m getting one at random. ThinkExist uses the content
to have the body of the quote and title
to have the author. A little bit of formatting, and we’re done.
1 2 3 4 5 6 |
$ ruby quotation.rb "There is no past that we can bring back by longing for it. There is only an eternally new now that builds and creates itself out of the Best as the past withdraws." -- Johann Wolfgang von Goethe (http://en.thinkexist.com/quotes/johann_wolfgang_von_goethe/) |
The code may be downloaded: quotation.rb
Enjoy!