Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Tim Morgan http://timmorgan.org

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Fix for ActiveRecord SQL Server adapter dates

The SQL Server adapter for ActiveRecord uses Time objects to cast dates from the db. This fails for dates before 1970, thus some birthdates come back as nil. This is some kludge to use a DateTime in that case so we still get the value.

A better approach may be to convert this code to use DateTime objects exclusively, but I'm not sure of the speed implications of doing so. The code below first tries to cast the value to a Time object; if that fails, it tries a DateTime object; if that fails, it returns nil.

Stick this in a plugin to use with Rails.

   1  
   2  module ActiveRecord
   3    module ConnectionAdapters
   4      class ColumnWithIdentity
   5        def cast_to_time(value)
   6          return value if value.is_a?(Time) or value.is_a?(DateTime)
   7          time_array = ParseDate.parsedate(value)
   8          time_array[0] ||= 2000
   9          time_array[1] ||= 1
  10          time_array[2] ||= 1
  11          Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
  12        end
  13        def cast_to_datetime(value)
  14          if value.is_a?(Time) or value.is_a?(DateTime)
  15            if value.year != 0 and value.month != 0 and value.day != 0
  16              return value
  17            else
  18              return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
  19            end
  20          end
  21          return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
  22          value
  23        end
  24      end
  25    end
  26  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS