The Dev Blog

Putting Family Management on Rails!

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?

  1. Create a new rails application: rails .

  2. Install the tzinfo plugin: script/plugin install tzinfo_timezone

  3. Edit app/controllers/application.rb

  4. 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
end

Now 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.

Posted in ,  | no comments

del.icio.us:A World Time Server In One Line Of Rails digg:A World Time Server In One Line Of Rails spurl:A World Time Server In One Line Of Rails wists:A World Time Server In One Line Of Rails simpy:A World Time Server In One Line Of Rails newsvine:A World Time Server In One Line Of Rails blinklist:A World Time Server In One Line Of Rails furl:A World Time Server In One Line Of Rails reddit:A World Time Server In One Line Of Rails fark:A World Time Server In One Line Of Rails blogmarks:A World Time Server In One Line Of Rails Y!:A World Time Server In One Line Of Rails smarking:A World Time Server In One Line Of Rails magnolia:A World Time Server In One Line Of Rails segnalo:A World Time Server In One Line Of Rails

Comments

Comments are disabled

Subscribe to The Dev Blog