Satchel
Satchel

Reputation: 16724

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

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?

Upvotes: 8

Views: 8838

Answers (6)

rewritten
rewritten

Reputation: 16435

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

Upvotes: 2

Marcin Urbanski
Marcin Urbanski

Reputation: 2493

Rails 5:

date.on_weekend?
date.on_weekday?

Rails 4:

date.saturday? || date.sunday?

Upvotes: 18

Srikanth Jeeva
Srikanth Jeeva

Reputation: 3011

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  

Upvotes: 2

Shreyas
Shreyas

Reputation: 8757

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.

Upvotes: 0

aarona
aarona

Reputation: 37263

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?

Upvotes: 1

Magnar
Magnar

Reputation: 28810

Like this:

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

mail_date += 1.days while weekend.include?(mail_date.wday)

Upvotes: 13

Related Questions