noizZze

Ruby + NASA = Nice Wallpapers

I have a link among my bookmarks to the great page – Astronomy Picture of the Day by NASA. Several times a week I visit this place to get a new charge of positive energy. It’s inconceivable that they have so many great shots from all over the universe!

As you might know if you are reading this blog that lately I got interested in Ruby. I’m a Linux guy and all these scriptic-cryptic languages are fun to learn for me, so I quickly jumped in the boots and found some applications for it including the one I wish to share with you today.

Below is a small Ruby application which is fetching the NASA’s page, parses it, takes the picture link, fetches the picture into some local file and sets it as a wallpaper for the Gnome desktop. Everything is in 7 lines of uncompressed code excluding initial setup, comments and white spaces. What would you say, heh? Fun, isn’t it? ;)

#!/usr/bin/env ruby
require 'net/http'
require 'uri'

# Absolute path to the place where to store pics
picture_root = '/home/aleksey/pics/astro/'

# Find URL, fetch file and set the background
sourceURL = 'http://antwrp.gsfc.nasa.gov/apod/astropix.html'
page = Net::HTTP.get(URI.parse(sourceURL))
imageTag = page.scan(/<img [^/>]+>/i)[0]
url = URI.parse(sourceURL.scan(/^.+//)[0] + imageTag.scan(/src="([^" mce_src="([^"]+)"/i)[0][0])

filename = picture_root + Time.now.strftime('%y%m%d') + ".jpg";
File.open(filename, 'w') { |file| file << Net::HTTP.get(url); }

`gconftool -t string -s /desktop/gnome/background/picture_filename #{filename}`