course_section.rb 2.13 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
28
29
30
31
  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
  
  def self.from_name(base_query, name)
    base_query.where("name LIKE ?", "%#{name}%")
  end
  
32
33
  # Select all revelevant course sections given the provided filters
  def self.fetch(filters)
34
35
36
37
    query = CourseSection.joins(:course).select("course_sections.*")
    if filters.include? "query"
      filters = CourseSection.parse_generic_query(filters["query"])
    end
38
    
39
40
41
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)
      when "name"
        query = from_name(query, value)
      when "subject"
        query = Course.from_subject(query, value)
49
50
      end
    end
51
52
    
    query
53
54
55
  end
    
  def self.parse_generic_query(query) 
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    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
    }
71
    
72
73
74
    # If it's not a number, just assume it's the name
    filters["name"] = query
    filters
75
76
  end
      
Zac Wood's avatar
Zac Wood committed
77
end