Recent Projects

Migrate to the Rails Default Time Zones

I was recently upgrading my open-source app, El Dorado, up to Rails 2.1 and decided to switch over to the default time zones provided by the Rails. I’m not sure where I picked up the time zone definitions I was using before, but they were things like “US/Central” as opposed to “Central Time (US & Canada)”.

Switching to the new time zone definitions provided by Rails means not having to rely on the TZInfo gem, because a stripped-down version is now packaged with Rails 2.1.

Here’s the migration used to achieve this, which was made with some help from Geoff Buesing himself:

# db/migrate/20080603023415_use_rails_new_default_time_zones.rb

class UseRailsNewDefaultTimeZones < ActiveRecord::Migration
  def self.up
    @users = User.all
    @users.each do |user|
      user.time_zone = 'UTC' if user.time_zone.blank?
      tz = TZInfo::Timezone.get(user.time_zone) rescue TimeZone[user.time_zone] || TimeZone['UTC']
      time_zone = if tz.is_a?(TZInfo::Timezone)
        linked_timezone = tz.instance_variable_get('@linked_timezone')
        name = linked_timezone ? linked_timezone.name : tz.name
        TimeZone::MAPPING.index(name)
      else
        tz.name
      end
      user.update_attribute(:time_zone, time_zone) unless time_zone == user.time_zone
    end unless @users.empty?
  end

  def self.down
  end
end

If you haven't played with the new time zone stuff in Rails 2.1, make sure to check it out. It makes dealing with time zones so easy, it's almost unbelievable. Thanks, Geoff!