Add ActiveSupport::TimeZone.country_zones helper

That helper will return time zones for any country that tzdata knows about.
So it will be much simpler for non-US people to list own country time zones
in HTML selects or anywhere.
上级 406a2380
* Add `ActiveSupport::TimeZone.country_zones` helper to retrieve time zones
for every country that tzdata knows about.
Make `ActiveSupport::TimeZone.us_zones` helper use it.
*Andrey Novikov*
* `Array#sum` compat with Ruby 2.4's native method.
Ruby 2.4 introduces `Array#sum`, but it only supports numeric elements,
......
......@@ -184,6 +184,7 @@ class TimeZone
UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.tr(':', '')
@lazy_zones_map = Concurrent::Map.new
@country_zones = Concurrent::Map.new
class << self
# Assumes self represents an offset from UTC in seconds (as returned from
......@@ -242,7 +243,18 @@ def [](arg)
# A convenience method for returning a collection of TimeZone objects
# for time zones in the USA.
def us_zones
@us_zones ||= all.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
country_zones(:us)
end
# A convenience method for returning a collection of TimeZone objects
# for time zones in the country specified by its ISO 3166-1 Alpha2 code.
def country_zones(country_code)
code = country_code.to_s.upcase
@country_zones[code] ||=
TZInfo::Country.get(code).zone_identifiers.map do |tz_id|
name = MAPPING.key(tz_id)
name && self[name]
end.compact.sort!
end
private
......
......@@ -491,6 +491,11 @@ def test_us_zones
assert !ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Kuala Lumpur"])
end
def test_country_zones
assert ActiveSupport::TimeZone.country_zones("ru").include?(ActiveSupport::TimeZone["Moscow"])
assert !ActiveSupport::TimeZone.country_zones(:ru).include?(ActiveSupport::TimeZone["Kuala Lumpur"])
end
def test_to_yaml
assert_equal("--- !ruby/object:ActiveSupport::TimeZone\nname: Pacific/Honolulu\n", ActiveSupport::TimeZone["Hawaii"].to_yaml)
assert_equal("--- !ruby/object:ActiveSupport::TimeZone\nname: Europe/London\n", ActiveSupport::TimeZone["Europe/London"].to_yaml)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册