Skip to content

Commit 2ae8300

Browse files
Serguei Filimonovgbuesing
authored andcommitted
Added #to_i to DateTime in ActiveSupport so #to_yaml works correctly on ActiveRecord models with DateTime attributes.
1 parent 7b61541 commit 2ae8300

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
require "cases/helper"
2+
require 'models/topic'
3+
4+
class YamlSerializationTest < ActiveRecord::TestCase
5+
def test_to_yaml_with_time_with_zone_should_not_raise_exception
6+
Time.zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"]
7+
ActiveRecord::Base.time_zone_aware_attributes = true
8+
topic = Topic.new(:written_on => DateTime.now)
9+
assert_nothing_raised { topic.to_yaml }
10+
end
11+
end

activesupport/lib/active_support/core_ext/date_time/conversions.rb

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,18 @@ def xmlschema
7878

7979
# Converts self to a floating-point number of seconds since the Unix epoch
8080
def to_f
81-
days_since_unix_epoch = self - ::DateTime.civil(1970)
82-
(days_since_unix_epoch * 86_400).to_f
81+
seconds_since_unix_epoch.to_f
82+
end
83+
84+
# Converts self to an integer number of seconds since the Unix epoch
85+
def to_i
86+
seconds_since_unix_epoch.to_i
87+
end
88+
89+
private
90+
91+
def seconds_since_unix_epoch
92+
seconds_per_day = 86_400
93+
(self - ::DateTime.civil(1970)) * seconds_per_day
8394
end
8495
end

activesupport/test/core_ext/date_time_ext_test.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,10 @@ def test_to_f
350350
assert_equal 946684800.0, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_f
351351
end
352352

353+
def test_to_i
354+
assert_equal 946684800, DateTime.civil(2000).to_i
355+
end
356+
353357
protected
354358
def with_env_tz(new_tz = 'US/Eastern')
355359
old_tz, ENV['TZ'] = ENV['TZ'], new_tz

0 commit comments

Comments
 (0)