Rails // daytime time zone request

Not sure when it comes to using time zones, looking for some help on this

I have a cron job that checks users every once in a while, which causes the rake task. As part of this rake task, I request users and send each email database on conditions.

I have time zone information for each user. I would like to receive a request for those users who will return only those users who are currently in the daytime

How to achieve this?

The best

+5
source share
1 answer

It depends on several different things, but I’ll talk about how my site is configured. My user model has a column named time zone, an example of how time intervals are stored in this column would be: "US / Central"

I would do this by collecting an array of timezone names that are currently within a specific time range, then query the user table.

zones = ActiveSupport::TimeZone.zones_map.values. map { |z| z.name if (8..20).cover?(z.now.hour) }.compact users = User.where(timezone: zones) 

The "zone_map.values" part will cancel the list of all time zones, then we will match them to return the names of those that currently have an hour between 8AM (8) and 8PM (20). Then we use the array returned by the map in the request for users.

So, "z.now" will give us the current time in this time zone, and we use '(8..20) .cover?' to find out if 'z.now.hour' is between 8 and 20.

** Hours above 12 will not reset to 1, but instead will continue as 13, 14, etc.

Not sure if there is a faster / more efficient way, but I found it to stay in the request and not let all users through.

+3
source

Source: https://habr.com/ru/post/1245563/


All Articles