11 Ağustos 2007 Cumartesi

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.

module ActiveRecord
module ConnectionAdapters
class ColumnWithIdentity
def cast_to_time(value)
return value if value.is_a?(Time) or value.is_a?(DateTime)
time_array = ParseDate.parsedate(value)
time_array[0] = 2000
time_array[1] = 1
time_array[2] = 1
Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
end
def cast_to_datetime(value)
if value.is_a?(Time) or value.is_a?(DateTime)
if value.year != 0 and value.month != 0 and value.day != 0
return value
else
return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
end
end
return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
value
end
end
end
end


0 Comments: