Rails 5.1 enhances ActiveSupport::TimeZone.country_zones

Narendra Rajput

By Narendra Rajput

on July 18, 2017

This blog is part of our  Rails 5.1 series.

The ActiveSupport::TimeZone class serves as wrapper around TZInfo::TimeZone class. It limits the set of zones provided by TZInfo to smaller meaningful subset and returns zones with friendly names. For example, TZInfo gem returns "America/New_York" whereas Active Support returns "Eastern Time (US & Canada)".

ActiveSupport::TimeZone.country_zones method returns a set of TimeZone objects for timezones in a country specified as 2 character country code.

1# Rails 5.0
2>> ActiveSupport::TimeZone.country_zones('US')
3
4=> [#<ActiveSupport::TimeZone:0x007fcc2b9b3198 @name="Hawaii", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: Pacific/Honolulu>>, #<ActiveSupport::TimeZone:0x007fcc2b9d9ac8 @name="Alaska", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: America/Juneau>>, #<ActiveSupport::TimeZone:0x007fcc2ba03a08 @name="Pacific Time (US & Canada)", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: America/Los_Angeles>>,...]

In Rails 5.0, the country_zones method returns empty for some countries. This is because ActiveSupport::TimeZone::MAPPING supports only a limited number of timezone names.

1
2>> ActiveSupport::TimeZone.country_zones('SV') // El Salvador
3
4=> []

Rails 5.1 fixed this issue. So now if the country is not found in the MAPPING hash then a new ActiveSupport::TimeZone instance for the country is returned.

1
2>> ActiveSupport::TimeZone.country_zones('SV') // El Salvador
3
4=> [#<ActiveSupport::TimeZone:0x007ff0dab83080 @name="America/El_Salvador", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: America/El_Salvador>>]

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.