course_section.rb 1.79 KB
Newer Older
Zac Wood's avatar
Zac Wood committed
1
2
# Contains logic belonging to the +CourseSection+ model.
class CourseSection < ApplicationRecord
3
  # Each +CourseSection+ belongs to a +Course+ and an +Instructor+.
Zac Wood's avatar
Zac Wood committed
4
  belongs_to :course
5
  belongs_to :instructor
Zac Wood's avatar
Zac Wood committed
6
7
8
9
10

  # Ensure all necessary fields are present.
  validates :name, presence: true
  validates :crn, presence: true
  validates :title, presence: true
11
  validates :course_id, presence: true
12

13
14
15
16
17
  def overlaps?(other)
    t1_start, t1_end = Time.parse(start_time), Time.parse(end_time)
    t2_start, t2_end = Time.parse(other.start_time), Time.parse(other.end_time)

    (t1_start <= t2_end && t2_start <= t1_end) && Set.new(days.split).intersect?(Set.new(other.days.split))
Zac Wood's avatar
Zac Wood committed
18
19
  end

20
  def self.latest_by_crn(crn)
Zac Wood's avatar
Zac Wood committed
21
    where(crn: crn).min_by { |s| s.course.semester.id }
22
23
  end

24
25
  # Select all course sections that have an instructor that matches the given name
  def self.with_instructor(name: "")
Zac Wood's avatar
Zac Wood committed
26
27
28
    joins(:instructor)
      .where("instructors.name LIKE ?", "%#{name}%")
      .select('course_sections.*, instructors.name as instructor_name')
29
  end
Zach Perkins's avatar
Zach Perkins committed
30

31
  def self.from_crn(base_query, crn)
Zac Wood's avatar
Zac Wood committed
32
    base_query.where(crn: crn)
33
  end
Zach Perkins's avatar
Zach Perkins committed
34

35
  def self.from_course_id(base_query, course_id)
Zac Wood's avatar
Zac Wood committed
36
    base_query.where(course_id: course_id)
37
  end
Zach Perkins's avatar
Zach Perkins committed
38

39
40
  # Select all revelevant course sections given the provided filters
  def self.fetch(filters)
41
    query = CourseSection.joins(:course).select("course_sections.*")
Zach Perkins's avatar
Zach Perkins committed
42

43
44
45
46
47
48
    filters.each do |filter, value|
      case filter
      when "crn"
        query = from_crn(query, value)
      when "course_id"
        query = from_course_id(query, value)
Zach Perkins's avatar
Zach Perkins committed
49
50
      when "course_number"
        query = Course.from_course_number(query, value)
51
52
      when "subject"
        query = Course.from_subject(query, value)
Zach Perkins's avatar
Zach Perkins committed
53
54
      when "title"
        query = Course.from_title(query, value)
55
56
      end
    end
Zach Perkins's avatar
Zach Perkins committed
57

58
    query
59
  end
Zac Wood's avatar
Zac Wood committed
60
end