Search code examples
ice-cube

Compare an array of dates to one day (in a rails calendar)


I'm using the calendar helper from Railscast: http://railscasts.com/episodes/213-calendars-revised but I'm running into a problem (calendar helper below):

module CalendarHelper

def calendar(date = Date.today, &block)
  Calendar.new(self, date, start_date, end_date, scheduled, block).table
end

class Calendar < Struct.new(:view, :date, :start_date, :end_date, :scheduled, :callback)
  HEADER = %w[S M T W T F S]
  START_DAY = :sunday

  delegate :content_tag, to: :view

def table
  content_tag :table, class: "calendar" do
    header + week_rows
  end
end

def header
  content_tag :tr do
    HEADER.map { |day| content_tag :th, day }.join.html_safe
  end
end

def week_rows
  weeks.map do |week|
    content_tag :tr do
      week.map { |day| day_cell(day) }.join.html_safe
    end
  end.join.html_safe
end

def day_cell(day)
  content_tag :td, view.capture(day, &callback), class: day_classes(day)
end

def day_classes(day)
  classes = []
  classes << "today" if day == Date.today
  classes << "start_date" if day == start_date
  classes << "end_date" if day == end_date
  classes << "notmonth" if day.month != date.month
  classes << "scheduled" if day == scheduled

  classes.empty? ? nil : classes.join(" ")
end

  def weeks
    first = date.beginning_of_month.beginning_of_week(START_DAY)
    last = date.end_of_month.end_of_week(START_DAY)
    (first..last).to_a.in_groups_of(7)
  end
 end
end

My application spits out an array of scheduled dates (using the ice_cube gem). For each one of those dates I want to match them with dates from the calendar, assigning them with the class "scheduled". I can't figure out how to do this. This code is what I'm trying to make work:

classes << "scheduled" if day == scheduled

'scheduled' comes from the controller:

Application_Controller.rb

def scheduled
  Schedule.find(params[:id]).itinerary.all_occurrences if params[:id]
end

helper_method :scheduled

Which returns the following array of dates:

 => [2014-05-16 00:00:00 -0400, 2014-05-19 00:00:00 -0400, 2014-05-20 00:00:00 -0400, 2014-05-21 00:00:00 -0400, 2014-05-22 00:00:00 -0400, 2014-05-23 00:00:00 -0400, 2014-05-26 00:00:00 -0400, 2014-05-27 00:00:00 -0400, 2014-05-28 00:00:00 -0400, 2014-05-29 00:00:00 -0400] 

I've tried a number of scenarios but I can't figure it out.

As an example, this will work and show the "scheduled" class for these 3 days but I can't figure out how to loop through all the scheduled dates and still have an || operator in the block:

def day_classes(day)
  ...
  classes << "scheduled" if Date.yesterday == day || Date.tomorrow == day || Date.today == day
  ...
end

Or maybe someone has a better idea?


Solution

  • After a bit of reading through the ice_cube gem I found a handy method that does exactly what I needed.

    def day_classes(day)
      ...
      classes << "scheduled" if scheduled.itinerary.occurs_on?(day)
      ...
    end