开发者

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

开发者 https://www.devze.com 2023-01-19 01:37 出处:网络
I have a message substitution called next_week which basically takes Date.today + 7.days. However, al开发者_如何学Cthough I still want to send emails on weekends, if the next_week falls on a weekend,

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

However, al开发者_如何学Cthough 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?


Rails 5:

date.on_weekend?
date.on_weekday?

Rails 4:

date.saturday? || date.sunday?


Like this:

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

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


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  


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


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消