1class Admin::Archived::PetitionsController < Admin::AdminController |
|
2 before_action :redirect_to_show_page, only: [:index], if: :petition_id? |
|
3 before_action :fetch_parliament, only: [:index] |
|
4 before_action :redirect_to_admin_hub, only: [:index], unless: :parliament_present? |
|
5 before_action :fetch_petitions, only: [:index] |
|
6 before_action :fetch_petition, only: [:show] |
|
8 rescue_from ActiveRecord::RecordNotFound do |
|
9 redirect_to admin_root_url, alert: "Sorry, we couldn't find petition #{params[:id]}" |
|
10 end |
|
12 def index |
|
13 respond_to do |format| |
|
14 format.html
|
|
15 format.csv { render_csv }
|
|
16 end |
|
17 end |
|
19 def show |
|
20 respond_to do |format| |
|
21 format.html
|
|
22 end |
|
23 end |
|
25 protected
|
|
27 def petition_id? |
|
28 /^\d+$/ =~ params[:q].to_s |
|
29 end |
|
31 def parliament_present? |
|
32 @parliament.present? |
|
33 end |
|
35 def redirect_to_show_page |
|
36 redirect_to admin_archived_petition_url(params[:q].to_i) |
|
37 end |
|
39 def redirect_to_admin_hub |
|
40 redirect_to admin_root_url, notice: "There are no archived petitions" |
|
41 end |
|
43 def scope |
|
44 if params[:match] == "none" |
|
45 @parliament.petitions.untagged |
|
46 elsif params[:tags].present? |
|
47 if params[:match] == "all" |
|
48 @parliament.petitions.tagged_with_all(params[:tags]) |
|
49 else |
|
50 @parliament.petitions.tagged_with_any(params[:tags]) |
|
51 end |
|
52 else |
|
53 @parliament.petitions.all |
|
54 end |
|
55 end |
|
57 def parliament_id |
|
58 params[:parliament].to_i |
|
59 end |
|
61 def fetch_parliament |
|
62 if params.key?(:parliament) |
|
63 @parliament = Parliament.archived.find(parliament_id) |
|
64 else |
|
65 @parliament = Parliament.archived.first |
|
66 end |
|
67 end |
|
69 def fetch_petitions |
|
70 @petitions = scope.search(params) |
|
71 end |
|
73 def fetch_petition |
|
74 @petition = ::Archived::Petition.find(params[:id]) |
|
75 end |
|
77 def render_csv |
|
78 set_file_headers
|
|
79 set_streaming_headers
|
|
81 #setting the body to an enumerator, rails will iterate this enumerator |
|
82 self.response_body = PetitionsCSVPresenter.new(@petitions).render |
|
83 end |
|
85 def set_file_headers |
|
86 headers["Content-Type"] = "text/csv" |
|
87 headers["Content-Disposition"] = "attachment; filename=#{csv_filename}" |
|
88 end |
|
90 def set_streaming_headers |
|
91 #nginx doc: Setting this to "no" will allow unbuffered responses suitable for Comet and HTTP streaming applications |
|
92 headers['X-Accel-Buffering'] = 'no' |
|
93 headers["Cache-Control"] ||= "no-cache" |
|
94 headers.delete("Content-Length") |
|
95 end |
|
97 def csv_filename |
|
98 "#{@petitions.scope.to_s.dasherize}-petitions-#{Time.current.to_s(:number)}.csv" |
|
99 end |
|
100end |