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

  # Ensure all necessary fields are present.
  validates :name, presence: true
  validates :crn, presence: true
  validates :title, presence: true
13
  validates :course_id, presence: true
14
15
16
17
18

  # Select all course sections that have an instructor that matches the given name
  def self.with_instructor(name: "")
    joins(:instructor).where("instructors.name LIKE ?", "%#{name}%").select('course_sections.*, instructors.name as instructor_name')
  end
19
  
20
21
22
23
24
25
26
27
  def self.from_crn(base_query, crn)
    base_query.where("course_sections.crn = ?", value)
  end
  
  def self.from_course_id(base_query, course_id)
    base_query.where("course_sections.course_id = ?")
  end
  
28
29
  # Select all revelevant course sections given the provided filters
  def self.fetch(filters)
30
31
32
33
    query = CourseSection.joins(:course).select("course_sections.*")
    if filters.include? "query"
      filters = CourseSection.parse_generic_query(filters["query"])
    end
34
    
35
36
37
38
39
40
    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
41
42
      when "course_number"
        query = Course.from_course_number(query, value)
43
44
      when "subject"
        query = Course.from_subject(query, value)
Zach Perkins's avatar
Zach Perkins committed
45
46
      when "title"
        query = Course.from_title(query, value)
47
48
      end
    end
49
50
    
    query
51
52
53
  end
    
  def self.parse_generic_query(query) 
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    filters = {}
    
    # If there is a number in the query
    /\d+/.match(query) { |a| 
      m = a.to_s
      if m.length == query.length # Does the number take up the entire query
        if m.length == 5 # Check if it is a CRN
          filters["crn"] = m
        else # Just assume course_id
          filters["course_id"] = Integer(m)
        end
  
        return filters
      end
    }
69
    
Zach Perkins's avatar
Zach Perkins committed
70
71
    # If it's not a number, just assume it's the title
    filters["title"] = query
72
    filters
73
74
  end
      
Zac Wood's avatar
Zac Wood committed
75
end