1require 'postcode_sanitizer' |
|
2require 'csv' |
|
4class LocalPetitionsController < ApplicationController |
|
5 before_action :sanitize_postcode, only: :index |
|
6 before_action :find_by_postcode, if: :postcode?, only: :index |
|
7 before_action :find_by_slug, only: [:show, :all] |
|
8 before_action :find_petitions, if: :constituency?, only: :show |
|
9 before_action :find_all_petitions, if: :constituency?, only: :all |
|
10 before_action :redirect_to_constituency, if: :constituency?, only: :index |
|
12 after_action :set_content_disposition, if: :csv_request?, only: [:show, :all] |
|
|
14 def index |
15 respond_to do |format| |
|
16 format.html
|
|
17 end |
|
18 end |
|
|
20 def show |
21 respond_to do |format| |
|
22 format.html
|
|
23 format.json
|
|
24 format.csv
|
|
25 end |
|
26 end |
|
|
28 def all |
29 respond_to do |format| |
|
30 format.html
|
|
31 format.json
|
|
32 format.csv
|
|
33 end |
|
34 end |
|
36 private
|
|
|
38 def sanitize_postcode |
39 @postcode = PostcodeSanitizer.call(params[:postcode]) |
|
40 end |
|
|
42 def postcode? |
43 @postcode.present? |
|
44 end |
|
|
46 def find_by_postcode |
47 @constituency = Constituency.find_by_postcode(@postcode) |
|
48 end |
|
|
50 def find_by_slug |
51 @constituency = Constituency.find_by_slug!(params[:id]) |
|
52 end |
|
|
54 def constituency? |
55 @constituency.present? |
|
56 end |
|
|
58 def find_petitions |
59 @petitions = Petition.popular_in_constituency(@constituency.external_id, 50) |
|
60 end |
|
|
62 def find_all_petitions |
63 @petitions = Petition.all_popular_in_constituency(@constituency.external_id, 50) |
|
64 end |
|
|
66 def redirect_to_constituency |
67 if Parliament.dissolved? |
|
68 redirect_to all_local_petition_url(@constituency.slug) |
|
69 else |
|
70 redirect_to local_petition_url(@constituency.slug) |
|
71 end |
|
72 end |
|
|
74 def csv_filename |
75 if action_name == 'all' |
|
76 "all-popular-petitions-in-#{@constituency.slug}.csv" |
|
77 else |
|
78 "open-popular-petitions-in-#{@constituency.slug}.csv" |
|
79 end |
|
80 end |
|
|
82 def set_content_disposition |
83 response.headers['Content-Disposition'] = "attachment; filename=#{csv_filename}" |
|
84 end |
|
85end |