Reputation: 1126
I'm building a school calendar that lists classes ("sections") and displays semester and exam dates for those classes. The calendar is fed a hash that is defined in the Section.rb
model:
def get_calendar
calendar = {}
calendar[:semesters] = Semester.where(section_id: self.id)
calendar[:exams] = Exam.where(section_id: self.id)
{ :calendar => calendar }
end
The Semester
and Exam
objects have a name
, start_date
and end_date
.
When looping through each day of the calendar, how can I check if there's a semester or exam with a start_date
or end_date
for that day of the loop?
If there is a semester or exam with either a start_date
or end_date
that matches the calendar date, I would to display the name.
The calendar dates and the start_date
and end_date
fields all use the Date
class (link).
I sincerely appreciate the help. I can clarify the question if needed :)
Thank you!
Upvotes: 1
Views: 156
Reputation: 121
Would the enumberable detect method work? http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-detect
So as your looping through your condition could be...
semesters.detect{|s| s.begin_date > cal_begin_date ... //more conditions here} &&
exams.detect{|e| e.begin_date > cal_begin_date ... //more conditions here}
Upvotes: 1
Reputation: 54882
Maybe you should re-think your hash, and use it this way:
def get_calendar
semesters = self.semesters
exams = self.exams
events = { }
(semesters + exams).each do |event|
start_date = event.start_date.to_s
events[start_date] ||= []
events[start_date] << event
end_date = event.end_date.to_s
events[end_date] ||= []
events[end_date] << event
end
events
end
And test the presence of an event in the loop that constructs the Calendar:
dates_of_calendar.each do |date|
if @events[date.to_s].present?
# well, there is an event happening for this date! treat it as your wishes!
end
# etc...
end
Upvotes: 1