Random images from Flickr with Ruby

Posted by ZedTuX 0n R00t on December 19, 2014

I wanted to have a bit of fun when writing my tests and have my users having random avatars. Like using the Faker gem but with images.

So how to get randomly images, without credentials (another dev or even the CI should be able to get an image without having to have an account somewhere) ?

RSS to the rescue

I was looking for an API without anthentication, but it seems to be hard today to find one. RSS is perfect for my case then :)

Which RSS with Ruby ?

3 years ago I was looking already for a modern Ruby gem RSS reader and never found the perfect one … so I made mine. The gem is called urss and is supporting RSS and Atom, plus it manage medias which is exactely the usecase here !

The installation is simple:

1
$ gem install urss

Now let’s play:

1
2
3
4
5
6
7
$ irb
2.1.5 :001 > require 'urss'
 => true
2.1.5 :002 > rss = Urss.at("http://www.flickr.com/services/feeds/photos_public.gne?format=rss_200"); true
 => true
2.1.5 :003 > rss.entries.first.medias.first.content_url
 => "http://farm9.staticflickr.com/8567/15434351784_d8a6e10b3c_b.jpg"

Nice, isn’t it ?

What about multiple users ?

As the RSS feed is sending 20 entires (you can check this with rss.entries.size), you have potentially 20 images.

1
2
2.1.5 :005 > rss.entries.map{ |entry| entry.medias.collect(&:content_url) }.flatten
 => ["http://farm9.staticflickr.com/8567/15434351784_d8a6e10b3c_b.jpg", "http://farm8.staticflickr.com/7503/15869184848_a71dbcbf6d_b.jpg", "http://farm8.staticflickr.com/7516/15869185428_8b61a6b9f1_b.jpg", "http://farm9.staticflickr.com/8583/15869185478_cef7ec7da8_b.jpg", "http://farm9.staticflickr.com/8678/15869353300_7e6687c918_b.jpg", "http://farm9.staticflickr.com/8678/15869353320_2b8121238c_b.jpg", "http://farm8.staticflickr.com/7502/15869353490_1954a114a6_b.jpg", "http://farm8.staticflickr.com/7517/15870876207_05e42d9dd8_b.jpg", "http://farm9.staticflickr.com/8673/15870876377_9b96cbfaea_b.jpg", "http://farm9.staticflickr.com/8610/15870876487_a08730cb0a_b.jpg", "http://farm9.staticflickr.com/8584/16030851846_6f90ccae4c_b.jpg", "http://farm9.staticflickr.com/8655/16030852406_85593385d9_b.jpg", "http://farm9.staticflickr.com/8608/16054683281_c23e210094_b.jpg", "http://farm8.staticflickr.com/7462/16054683321_0e683776b9_b.jpg", "http://farm8.staticflickr.com/7565/16054683441_19f9524f9d_b.jpg", "http://farm9.staticflickr.com/8564/16054683611_f30a4d4fde_b.jpg", "http://farm8.staticflickr.com/7536/16055944832_b34eddee48_b.jpg", "http://farm9.staticflickr.com/8593/16056639605_52901c26ef_b.jpg", "http://farm8.staticflickr.com/7484/16056639795_8cf42e43ab_b.jpg", "http://farm8.staticflickr.com/7564/16056640205_375ba20ea1_b.jpg"]