implement saved searches(filters)
[shapado:piglops-shapado.git] / app / controllers / searches_controller.rb
1 class SearchesController < ApplicationController
2   before_filter :login_required, :except => %w[index]
3
4   subtabs :index => [[:newest, %w(created_at desc)], [:hot, [%w(hotness desc), %w(views_count desc)]], [:votes, %w(votes_average desc)], [:activity, %w(activity_at desc)], [:expert, %w(created_at desc)]],
5           :unanswered => [[:newest, %w(created_at desc)], [:votes, %w(votes_average desc)], [:mytags, %w(created_at desc)]],
6           :show => [[:votes, %w(votes_average desc)], [:oldest, %w(created_at asc)], [:newest, %w(created_at desc)]]
7
8   def index
9     options = {:per_page => 25, :page => params[:page] || 1}
10     unless params[:q].blank?
11       pharse = params[:q]
12       @search_tags = pharse.scan(/\[(\w+)\]/).flatten
13       @search_text = pharse.gsub(/\[(\w+)\]/, "")
14       options[:tags] = {:$all => @search_tags} unless @search_tags.empty?
15       options[:group_id] = current_group.id
16       options[:banned] = false
17
18       if params[:language]
19         pharse += " lang:#{params[:language]}"
20       end
21
22       if params[:accepted]
23         pharse += " is:accepted"
24       end
25
26       if params[:answered]
27         pharse += " is:answered"
28       end
29
30       @search = Search.new(:query => pharse)
31
32       if !@search_text.blank?
33         @questions = Question.filter(@search_text, options)
34
35         @highlight = @questions.parsed_query[:tokens].to_a
36       else
37         @questions = Question.paginate(options)
38       end
39     else
40       @questions = []
41     end
42
43     respond_to do |format|
44       format.html
45       format.js do
46         render :json => {:html => render_to_string(:partial => "questions/question",
47                                                    :collection  => @questions)}.to_json
48       end
49       format.json { render :json => @questions.to_json(:except => %w[_keywords slugs watchers]) }
50     end
51   end
52
53   def show
54     @search = current_user.searches.by_slug(params[:id], :group_id => current_group.id)
55
56     find_questions(@search.conditions)
57   end
58
59   def create
60     @search = Search.new
61     @search.safe_update(%w[name query], params[:search])
62     @search.user = current_user
63     @search.group = current_group
64
65     respond_to do |format|
66       if @search.save
67         format.html { redirect_to search_path(@search) }
68       else
69         format.html do
70           params[:q] = @search.query
71           render 'index'
72         end
73       end
74     end
75   end
76
77   def destroy
78     @search = current_user.searches.by_slug(params[:id], :group_id => current_group.id)
79     @search.destroy
80
81     respond_to do |format|
82       format.html { redirect_to root_path }
83     end
84   end
85 end