Commit 1033073a authored by Zach Perkins's avatar Zach Perkins
Browse files

Perfected fetch for course

parent cd3a033a
......@@ -8,8 +8,8 @@ class CourseSectionsController < ApplicationController
api :GET, '/courses_sections', 'Get a list of course sections'
param :course_id, Integer, desc: "Only get the course sections belonging to the course with this ID"
param :crn, String, desc: "Get the course section with this CRN"
param :query, String, desc: 'A generic query ex. "CS 110"'
param :instructor, String, desc: "Get course sections being taught by this instructor"
param :query, String, desc: 'A generic query ex. "CS 110"'
def index
@sections = CourseSection.with_instructor(name: params[:instructor])
......@@ -7,13 +7,9 @@ class CoursesController < ApplicationController
api :GET, '/courses', "Get a list of courses."
param :subject, String, desc: 'Course subject, e.g. "CS" or "ACCT"'
param :course_number, Integer, desc: 'Course number, e.g. "112"'
param :query, String, desc: 'A generic query ex. "CS 110"'
def index
@courses = Course.all
# filter by subject + course number if the params are included
@courses = @courses.where(subject: params[:subject].upcase) if params.key?(:subject)
@courses = @courses.where(course_number: params[:course_number]) if params.key?(:course_number)
@courses = Course.fetch(params)
render json: @courses
......@@ -17,17 +17,35 @@ class Course < ApplicationRecord
CourseSection.where course_id: id
def fetch(filters)
# 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)
query ="*")
filter_list = Course.parse_generic_query(filters["query"]) if filters.include? "query" else filters
filters.each do |filter, value|
filter_list.each do |filter, value|
if Course.column_names.include? filter
case filter
when :subject
query.where("subject = ?", value)
when :course_number
query.where("course_number = ?", value)
when "subject"
query = query.where("subject = ?", value.upcase)
when "course_number"
query = query.where("course_number = ?", value)
return query.all
# 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
# include class names
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
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment