class Faker::Date

def on_day_of_week_between(day:, from:, to:)

Other tags:
    Example: if used with Rails (Active Support) -
    Example: if used with or without Rails (Active Support) -

Returns:
  • (Date) -

Parameters:
  • to (Date, String) -- The end of the usable date range.
  • from (Date, String) -- The start of the usable date range.
  • day (Symbol, Array) -- # The day(s) of the week. See {DAYS_OF_WEEK}.
def on_day_of_week_between(day:, from:, to:)
  days = [day].flatten
  raise ArgumentError, 'Day of week cannot be empty' if days.empty?
  # Convert given days of the week to numbers used by `Date#wday` method
  numeric_weekdays = days.map do |d|
    DAYS_OF_WEEK.index(d.to_sym.downcase) || raise(ArgumentError, "#{d} is not a valid day of the week")
  end
  from = get_date_object(from)
  to   = get_date_object(to)
  date = Faker::Base.rand_in_range(from, to)
  # If the initial date is not on one of the wanted days of the week...
  unless numeric_weekdays.include? date.wday
    # ...pick a date nearby that is on one of the wanted days of the week instead
    date += sample(numeric_weekdays) - date.wday
    # Move date 1 week earlier or later if the adjusted date is now outside the date range
    date += 7 if date < from
    date -= 7 if date > to
    if date > to || date < from
      raise ArgumentError,
            "There is no #{DAYS_OF_WEEK[date.wday].capitalize} between #{from} and #{to}. Increase the from/to date range or choose a different day of the week."
    end
  end
  date
end