简体   繁体   中英

Preventing an action during specific hours of the day (Rails)

I'm fairly sure there's a straightforward strategy for this, but I can't find an example of how it's been implemented so I wanted to post something to see if anyone else has had success doing it:

I'm working on a Rails 6 app that allows external users to place calls to members of the application - like an app that allows a user from the web to call a salesperson. We're wanting to limit the hours during which those calls are able to be made to the member. ie, a specific member only wants to receive calls during business hours.

I have a pretty solid time zone strategy to handle the conversion from GMT to local, so that shouldn't be an issue - what I'm struggling to figure out is a best practice to save a member's "start time" and "end time" for receiving calls. FWIW, I have a call model, and when a call is placed it's done through the rails create action. Obviously, this couldn't be a DateTime, because it's not a specific day, it's a range of hours they're willing to accept calls.

Here's my best thinking thus far: Members have a start_time and end_time attributes - probably integers of the hour of the day (08, 10, 14, 20, etc.) There's a before_action in the call model that compares the current time, stripped to the hour of the day (%H), to see if it's greater than the start_time and less than the end_time .

Could be as simple as wrapping it in an if statement:

if Time.now.between?(Time.parse(@member.start_time), Time.parse(@member.end_time))

This would allow you to store the times as strings like "08:00" and "21:00". A member could be exact with their time like "08:45" and "17:15". But Time.now can get tricky so as you stated best to always work with time zones.

If you store the member's time zone offset with their times like "08:45 -08:00" and "18:45 -08:00" you can do the above and it will work.

 if Time.zone.now.between?(Time.parse(@member.start_time), Time.parse(@member.end_time))

Or you can store the person's time zone instead of the offset like "08:00 PDT" and "18:00 PDT" and it will work. You may need to use TZInfo for dealing with places that observe DST. I highly recommend this article: https://thoughtbot.com/blog/its-about-time-zones

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM