search_helper.rb 2.13 KB
Newer Older
Zac Wood's avatar
Zac Wood committed
1
module SearchHelper
2
3
4
5
6
7
8
9
  class GenericItem
    def initialize(type, data)
      @type = type
      @data = data
    end
    
    def self.fetchall(query_string)
      models = []
10
11
      models += fetch_instructors query_string
      models += fetch_courses query_string
12
13
14
15
16
17
18
19
20
21
      build_list(models)
    end
    
    def self.fetch_instructors(query_string)
      Instructor.from_name(Instructor.select("*"), query_string).all
    end
    
    def self.fetch_courses(query_string)
      query_string.upcase!
      CourseReplacementHelper.replace!(query_string)
22
23
24
25
      base_query = Course.select("courses.*, count(course_sections.id) AS section_count")
                         .left_outer_joins(:course_sections)
                         .having("section_count > 0")
                         .group("courses.id")
26
27
28
29
  
      subj = nil
      query_string.scan(/(?<= |^)([a-zA-Z]{2,4})(?=$| )/).each do |a|
        s = a[0]
30
        if get_count(Course.from_subject(base_query, s)).positive?
31
32
33
34
35
36
37
38
          subj = s
          base_query = Course.from_subject(base_query, subj)
          query_string.remove!(s)
        end
      end
   
      query_string.scan(/(?<= |^)(\d{3})(?=$| )/).each do |a|
        s = a[0]
39
40
41
        next unless !subj.nil? && get_count(Course.from_course_number(base_query, s)).positive?
        base_query = Course.from_course_number(base_query, s)
                           .order("courses.course_number ASC")
42
43
44
        return base_query.all
      end
      
45
46
47
      base_query = Course.from_title(base_query, query_string.gsub(/ +/, " ").strip)
                         .order("section_count DESC")
        
48
49
50
51
52
53
54
55
      base_query.all
    end
      
    
    # Given a set of models, create a list of GenericItems for each model's data
    def self.build_list(models)
      list = []
      models.each do |model|
56
        list.push(GenericItem.new(model.class.name.underscore, model))
57
58
59
60
      end
      
      list
    end
61
62
63
64
65
66
67
68
69
    
    def self.get_count(base_query)
      # I think I finally hit a limit of active record
      ActiveRecord::Base.connection.execute("SELECT COUNT(*) AS count FROM (#{base_query.to_sql})")[0]["count"]
    end
    
    def to_s()
      @type
    end
70
  end
Zac Wood's avatar
Zac Wood committed
71
end