search_controller.rb 1.87 KB
Newer Older
Zac Wood's avatar
Zac Wood committed
1 2
class SearchController < ApplicationController
  def index
Zac Wood's avatar
Zac Wood committed
3
    redirect_to(home_url) unless params[:query].length > 1
Zac Wood's avatar
Zac Wood committed
4

Zac Wood's avatar
Zac Wood committed
5 6 7 8 9
    if params[:query].casecmp('god').zero?
      bell = Instructor.find_by_name('Jonathan Bell')
      redirect_to(instructor_url(bell))
    end

Zac Wood's avatar
Zac Wood committed
10 11
    @instructors = nil
    @courses = nil
Zac Wood's avatar
Zac Wood committed
12

Zac Wood's avatar
Zac Wood committed
13 14 15
    /[[:alpha:]]{2,4} \d{3}/.match(params[:query]) do |m|
      subj, num = m[0].split(' ')
      course = Course.find_by(subject: subj.upcase, course_number: num)
16
      redirect_to(course_url(course)) unless course.nil?
Zac Wood's avatar
Zac Wood committed
17 18 19 20
    end

    /[[:alpha:]]{2,4}/i.match(params[:query]) do |m|
      @courses = Course.where(subject: m[0].upcase)
21 22 23
                       .joins(:course_sections)
                       .merge(CourseSection.in_semester(@semester))
                       .uniq
Zac Wood's avatar
Zac Wood committed
24 25 26

      if @courses.empty?
        @courses = Course.where("(courses.title LIKE ?)", "%#{params[:query]}%")
27 28 29
                         .joins(:course_sections)
                         .merge(CourseSection.in_semester(@semester))
                         .uniq
Zac Wood's avatar
Zac Wood committed
30 31

        other = Course.where("(courses.description LIKE ?)", "%#{params[:query]}%")
32 33 34
                      .joins(:course_sections)
                      .merge(CourseSection.in_semester(@semester))
                      .uniq
Zac Wood's avatar
Zac Wood committed
35 36 37 38 39

        @courses = [*@courses, *other].uniq

        @instructors = Instructor.named(params[:query])
      end
40 41 42 43 44

      @courses.map! do |c|
        c.serializable_hash.merge(url: course_url(c))
      end
      gon.courses = @courses
45
      gon.instructors = @instructors
Zac Wood's avatar
Zac Wood committed
46 47 48
    end

    /[0-9]{5}/.match(params[:query]) do |m|
49
      redirect_to(course_url(CourseSection.latest_by_crn(m[0]).course))
Zac Wood's avatar
Zac Wood committed
50 51
    end

52 53 54
    if @courses&.count == 1 && @instructors&.count&.zero?
      redirect_to course_url(@courses.first["id"])
    elsif @courses&.count&.zero? && @instructors&.count == 1
Zac Wood's avatar
Zac Wood committed
55 56
      redirect_to instructor_url(@instructors.first)
    end
Zac Wood's avatar
Zac Wood committed
57 58
  end
end