This post originated from an RSS feed registered with Ruby Buzz
by Guy Naor.
Original Post: A World Time Server In One Line Of Rails
Feed Title: Famundo - The Dev Blog
Feed URL: http://devblog.famundo.com/xml/rss/feed.xml
Feed Description: A blog describing the development and related technologies involved in creating famundo.com - a family management sytem written using Ruby On Rails and postgres
First, sorry for the delay in posting more on the XMPP/Jabber serie. I was a bit busy. So until I write the next instalment, here's a small piece of rails coolness.
Want to know the exact tiem 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_timerender:text=>TzinfoTimezone[params[:id]].utc_to_local(Time.now.getutc).strftime('%Y-%m-%d %H:%M:%S')rescuerender:text=>"ERROR - check your time zone",:status=>500end
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.