Skip to content

Commit 2627134

Browse files
jhawthornjasonkim
andcommitted
Add ActiveSupport::TimeZone#abbr
As of Ruby 2.6, ::Time supports rich timezone objects and expects them to follow a similar API to tzinfo. Mostly we already do this with ActiveSupport::TimeZone, delegating to the underlying tzinfo object, except we were missing the API to display the timezone's name. Calling strftime with "%Z" will try the following on the timezone: * zone.abbr(time) * zone.strftime("%Z", time) * zone.name Because we only implemented name, a ::Time created with an ActiveSupport::TimeZone would "abbreviate" awkwardly to the full tz identifier (like "12:34:00 America/Vancouver" instead of "12:34:00 PDT"). This commit implements abbr to make these Times format the same way as TimeWithZone. Co-authored-by: Jason Kim <[email protected]>
1 parent 8159498 commit 2627134

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

activesupport/lib/active_support/values/time_zone.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,12 @@ def periods_for_local(time) # :nodoc:
568568
tzinfo.periods_for_local(time)
569569
end
570570

571+
# Available so that TimeZone instances respond like +TZInfo::Timezone+
572+
# instances.
573+
def abbr(time)
574+
tzinfo.abbr(time)
575+
end
576+
571577
def init_with(coder) # :nodoc:
572578
initialize(coder["name"])
573579
end

activesupport/test/time_zone_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -876,4 +876,14 @@ def test_yaml_load
876876
loaded = YAML.respond_to?(:unsafe_load) ? YAML.unsafe_load(payload) : YAML.load(payload)
877877
assert_equal(ActiveSupport::TimeZone["Pacific/Honolulu"], loaded)
878878
end
879+
880+
def test_abbr
881+
zone = ActiveSupport::TimeZone["America/Toronto"]
882+
assert_equal "EST", zone.abbr(Time.utc(2000, 4, 2, 6))
883+
assert_equal "EDT", zone.abbr(Time.utc(2000, 4, 2, 7))
884+
assert_equal "EDT", zone.abbr(Time.utc(2000, 4, 2, 8))
885+
assert_equal "EDT", zone.abbr(Time.utc(2000, 10, 29, 5))
886+
assert_equal "EST", zone.abbr(Time.utc(2000, 10, 29, 6))
887+
assert_equal "EST", zone.abbr(Time.utc(2000, 10, 29, 7))
888+
end
879889
end

0 commit comments

Comments
 (0)