A World Time Server In One Line Of Rails
Posted by Guy Naor Thu, 09 Nov 2006 15:26:00 GMT
First, sorry for the delay in posting more on the XMPP/Jabber serie. I was a bit busy. So until I write the next installment, here's a small piece of rails coolness.
Want to know the exact time anywhere in the world? Including daylight saving taken into account? How about doing it in one line of rails code?
Create a new rails application: rails .
Install the tzinfo plugin: script/plugin install tzinfo_timezone
Edit app/controllers/application.rb
Add to it the following method (ok, it's 3 lines if we count the def and the end and not try to squeeze it into one with ; ):
def get_time
render :text => TzinfoTimezone[params[:id]].utc_to_local(Time.now.getutc).strftime('%Y-%m-%d %H:%M:%S') rescue render :text => "ERROR - check your time zone", :status => 500
endNow run it: script/server
Browse to: http://localhost:3000/application/get_time/Tokyo or http://localhost:3000/application/get_time/London. Check out the tzinfo plugin for the names of the supported time-zones. And you can add more to the mapping there.
You can improve performance a bit by turning sessions off completely. Do that either in the configuration or by adding session :off to the application controller class.
If you keep your computer clock accurate with ntp, you will get a pretty accurate time. The request is processed at a really high speed, so that shouldn't be a problem. And if the round trip to the server and back is quick, you will have a 1 second accuracy. Not bad for one line of code.

















