Skip to content

Instantly share code, notes, and snippets.

@dreki
Created June 20, 2012 20:12
Show Gist options
  • Save dreki/2961926 to your computer and use it in GitHub Desktop.
Save dreki/2961926 to your computer and use it in GitHub Desktop.
Fix for unexpected :time column behavior in Rails 3.2
module DstHelper
# Have a Time inherit DST status from a Date.
def inherit_dst date, time
time = time.change(:year => date.year, :month => date.mon, :day => date.day)
end
def self.included includer
# Mix in class methods.
includer.extend ClassMethods
end
module ClassMethods
# For ActiveRecord models only.
def applies_dst options={:from => nil, :to => nil}
from = options[:from]
to = options[:to]
define_method("#{to}=") do |new_value|
# Clear date information away from a Time object, so the correct value
# is returned without having to #reload the object.
self[to] = new_value.change :year => 2000, :month => 1, :day => 1
end
define_method(to) do
from_value = self[from]
to_value = self[to]
if from_value and to_value
inherit_dst(from_value, to_value).in_time_zone
else
# "Raw" value.
to_value.in_time_zone
end
end
end
end
end
@dreki
Copy link
Author

dreki commented Jun 20, 2012

Create a file at lib/dst_helper.rb with the above code. Apply in your models by doing this:

class MyModel < ActiveRecord::Base
  include DstHelper

  applies_dst :from => :date, :to => :time
end

Now, when you access my_model.time, you'll get what you expect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment