course.rb 1.78 KB
Newer Older
Zac Wood's avatar
Zac Wood committed
1
2
3
# Contains logic regarding the +Course+ model.
#
# TODO: Add more docs
Zac Wood's avatar
Zac Wood committed
4
class Course < ApplicationRecord
Zac Wood's avatar
Zac Wood committed
5
  # Each course belongs to a +Semester+
Zac Wood's avatar
Zac Wood committed
6
  belongs_to :semester
7
  has_many :course_sections
Zac Wood's avatar
Zac Wood committed
8

9
  # Ensure all necessary are fields present.
Zac Wood's avatar
Zac Wood committed
10
11
12
13
  validates :course_number, presence: true
  validates :subject, presence: true
  validates :semester_id, presence: true

Zac Wood's avatar
Zac Wood committed
14
  # Returns all +CourseSection+ objects that belong to this course.
15
  # @return [Array]
Zac Wood's avatar
Zac Wood committed
16
17
  def course_sections
    CourseSection.where course_id: id
Zac Wood's avatar
Zac Wood committed
18
  end
Zach Perkins's avatar
Zach Perkins committed
19
  
20
21
22
23
24
25
26
27
  def self.from_subject(base_query, subject)
    base_query.where("courses.subject = ?", subject.upcase)
  end
  
  def self.from_course_number(base_query, course_number)
    query = query.where("courses.course_number = ?", value)
  end
  
Zach Perkins's avatar
Zach Perkins committed
28
29
30
  # Given a list of filters, collect a list of matching elements. This makes it
  # so you can just pass the arguments straight thru
  def self.fetch(filters)
Zach Perkins's avatar
Zach Perkins committed
31
    query = Course.select("*")
32
33
34
35
36
    if filters.include? "query"
      filters = Course.parse_generic_query(filters["query"])
    end

    filters.each do |filter, value|
Zach Perkins's avatar
Zach Perkins committed
37
38
      if Course.column_names.include? filter
        case filter
Zach Perkins's avatar
Zach Perkins committed
39
        when "subject"
40
          query = from_subject(query, value)
Zach Perkins's avatar
Zach Perkins committed
41
        when "course_number"
42
          query = from_course_number(query, value)
Zach Perkins's avatar
Zach Perkins committed
43
44
45
        end
      end
    end
Zach Perkins's avatar
Zach Perkins committed
46
    
47
    query
Zach Perkins's avatar
Zach Perkins committed
48
49
50
51
52
53
  end
  
  # Splits a generic string (i.e. "CS 211") into a series of components that can
  # be used to run a query with fetch()
  def self.parse_generic_query(query)
    # In the future when there is more info, this will be more complex to
54
    # include class names/descriptions
Zach Perkins's avatar
Zach Perkins committed
55
56
57
58
59
60
    filters = {}
    q = query.gsub(" ", "")
    /[a-zA-Z]+/.match(q) { |a| filters["subject"] = a.to_s }
    /\d+/.match(q) { |a| filters["course_number"] = a.to_s }
    return filters
  end
Zac Wood's avatar
Zac Wood committed
61
end