Time zone check valid on rails

I am using tsjzt: http://pellepim.bitbucket.org/jstz/ on the client side to capture the time zone of the current users, which I store in my user object.

It works great and gives me time like Europe / London. I want to check when it will be passed to the model that it is a valid time zone if something bad happens.

So, I found this question: Report a custom timezone check for a Rails application on Heroku and tried this check:

validates_inclusion_of :timezone, :in => { in: ActiveSupport::TimeZone.zones_map(&:name) } 

However, the name is different from tzinfo. I think that my client side discovered the time line "Europe / London", in fact, is a component of the value of the TimeZone display in the TimeZone class, and not the name, which in this case will be set to "London".

So, I tried this:

 validates_inclusion_of :timezone, :in => { in: ActiveSupport::TimeZone.zones_map(&:tzinfo) } 

None of the original answers to another SO question or mine modified from :tzinfo work, as they both fail to check when: the time zone is β€œEurope / London”, when, obviously, it is a valid time zone!

What am I doing wrong with this time zone check and how to fix it?

+10
ruby datetime validation ruby-on-rails ruby-on-rails-4
source share
1 answer

Looks like you want this:

 validates_inclusion_of :timezone, :in => ActiveSupport::TimeZone.all.map { |tz| tz.tzinfo.name } 

On my machine, this list includes the following names:

 ... "Europe/Istanbul", "Europe/Kaliningrad", "Europe/Kiev", "Europe/Lisbon", "Europe/Ljubljana", "Europe/London", ... 

However, a cleaner solution would be a custom validation method, for example:

 validates_presence_of :timezone validate :timezone_exists private def timezone_exists return if timezone? && ActiveSupport::TimeZone[timezone].present? errors.add(:timezone, "does not exist") end 

This is more flexible in the values ​​it takes:

 ActiveSupport::TimeZone["London"].present? # => true ActiveSupport::TimeZone["Europe/London"].present? # => true ActiveSupport::TimeZone["Pluto"].present? # => false 
+15
source share

All Articles