RSS
21 Jan 2008

Sexy Time Zones in Ruby on Rails with Timezone_Fu

Author: ceefour | Filed under: Cool, Plugins, Rails, Ruby, Tips, Tools, Web 2.0

As easy as:
has_timezone :fields => [ :start_datetime, :end_datetime]
Timezone_fu makes it really easy to deal with datetime fields in your models. It adds a method to your models, has_timezone.

The README for the plugin describes all of the options but below is an example:

class Event < ActiveRecord::Base
    has_timezone :fields => [ :start_datetime, :end_datetime]
end

The model has three fields a start_datetime and end_datetime and a timezone. Adding has_timezone to the model changes the behavior of the two datetime attributes.
Notice below that calling event.start_datetime shows the time in local time (”America/New York”).

>> event = Event.find(:first)=> #<Event:0×1b71b40 @attributes={
       “end_datetime”   => “2007-11-21 15:00:00″,
      “start_datetime” => “2007-11-21 14:15:00″,
      “timezone”       => “America/New_York”}
>> event.start_datetime
=> Wed Nov 21 09:15:00 UTC 2007
>> event.display_start_datetime
=> “Nov. 21, 2007 09:15 AM”
>> event.utc_start_datetime
=> Wed Nov 21 14:15:00 UTC 2007

You can also set the value of the field to a local date/time and it will be converted to UTC automatically:

>> event.start_datetime = Time.now
=> Sun Nov 25 06:26:35 +0000 2007
=> #<Biz::Event:0×1b71b40 @attributes={
  “end_datetime”    =>  “2007-11-21 15:00:00″
  “start_datetime”  =>  Sun Nov 25 11:26:35 +0000 2007,
  “timezone”        =>  “America/New_York” } 

If you want to access the fields and retrieve the database value you can use the utc_field_name method to access the UTC value of the attribute. The plugin makes a couple of core assumptions. One it assumes that the default rails timezone is UTC:

ENV[‘TZ’] = ‘UTC’

Second it assumes that the model has a timezone attribute named timezone:

t.column :timezone, :string, :default => ”

Read more on: hackd.wordpress homepage.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Tags: 296, 299, 315, 316, 344, 361, 362, 363

blog comments powered by Disqus