Created
June 20, 2012 20:12
-
-
Save dreki/2961926 to your computer and use it in GitHub Desktop.
Fix for unexpected :time column behavior in Rails 3.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create a file at lib/dst_helper.rb with the above code. Apply in your models by doing this:
Now, when you access my_model.time, you'll get what you expect.