In my Rails app I need to get the dates for the next occurrence of a particular weekday starting from some other date. So basically I need date.next_monday, date.next_wednesday type functions. I don’t think these exist in standard Ruby libraries so I decided to monkey patch the Date class like so:
class Date
weekdays = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday]
weekdays.each do |weekday|
method_name = "next_" + weekday.to_s
send :define_method, method_name do
tmp_date = self + 1
until tmp_date.send((weekday.to_s + "?").to_sym)
tmp_date = tmp_date + 1
end
tmp_date
end
end
end
This seems to work fine.
My questions are:
- Did I not need to do all that? (Is there some way to get next_ that I’m not thinking of?
- If what I did is necessary, is there a better way to get the weekdays array?
Thanks!
The
Dateclass defines aDAYNAMESconstant (as well as a number of other useful constants) that you could use to replace your array.