how can I make sure a day is a weekday in Rails?
Asked Answered
E

6

8

I have a message substitution called next_week which basically takes Date.today + 7.days.

However, although I still want to send emails on weekends, if the next_week falls on a weekend, I want it to know this and push to the Monday.

How do i do this?

Ellita answered 4/10, 2010 at 4:36 Comment(0)
R
18

Rails 5:

date.on_weekend?
date.on_weekday?

Rails 4:

date.saturday? || date.sunday?
Roubaix answered 21/6, 2016 at 19:19 Comment(2)
I like these! it looks like the saturday? and any weekday? method is implemented in Ruby 1.9+, maybe earlier, on the Time and Date classes. Man, that would have been useful to know a couple of years ago :) Thanks @marcinCrinkleroot
Oh I assume this is in active support? I am not using rails.Ellita
M
13

Like this:

sunday = 0
saturday = 6
weekend = [saturday, sunday]

mail_date += 1.days while weekend.include?(mail_date.wday)
Misdeal answered 4/10, 2010 at 4:45 Comment(0)
D
2

You can Use this ,

def weekday?   
  (1..5).include?(wday)   
end  

check ..

d = Date.today   
=> Mon, 04 Oct 2010   
d.weekday?   
=> true   
d = Date.today - 1   
=> Sun, 03 Oct 2010   
d.weekday?   
=> false  
Darill answered 4/10, 2010 at 6:6 Comment(0)
C
2

Generally, use the business_time gem (https://github.com/bokmann/business_time), which will solve this issue in a complete way. This library will allow you to adapt for different work weeks (Sundays to Thursdays for instance) and even check if the hour is out of working hours.

Your case would be

def next_week
  0.business_days.after(7.days.from_now)
end
Crap answered 27/7, 2017 at 11:14 Comment(0)
A
1
mail_date = Date.today + 7.days
if mail_date.wday == 0
  mail_date += 1.day
elsif mail_date.wday == 6
  mail_date += 2.days
end

# now send your email on mail_date

Is this helpful?

Against answered 4/10, 2010 at 4:43 Comment(1)
I didn't know what is a feature. Let me try.Ellita
C
0

You can use Action Mailer Queue. Your mails are added to a queue and whenever you call ActionMailer Queue's method, the emails will be sent. So, basically you can call that method every weekday. On weekends, your emails will be added to the queue but won't be sent. On monday when you make the call to the method, your mails will be sent. Of course you can schedule your Action mailer method calls , to be called automatically every week day using a rake task or Rufus Scheduler.

Cupid answered 4/10, 2010 at 5:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.