aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/exports_controller.rb
blob: 975293bfd5b32098e13c3ce2328111a2fc3e2c53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

class ExportsController < ApplicationController
  before_action :set_search
  before_action :set_results, only: %i[show]

  def show
    respond_to do |format|
      format.csv { set_file_name!(ext: 'csv') }
      format.uoc { set_file_name!(ext: 'tex') }
      format.text do
        send_data PlainExporter.new(things: @results).export,
                  type:        'text/plain',
                  disposition: 'attachment',
                  filename:    "#{@search.name}.txt"
      end
    end
  end

  def new; end

  protected

  # Sets the file name for the attachment according to the @search's name, and
  # it adds the given string `ext` as the extension.
  def set_file_name!(ext:)
    response.headers['Content-Disposition'] = "attachment; filename=\"#{@search.name}.#{ext}\""
  end

  # Set @search. If there was no `:search_id` parameter, then we assume that the
  # ID = 0, which is the fake search we use for the base 'Home' (i.e. get
  # everything).
  def set_search
    @search = if params[:search_id].to_i.zero?
                Search.new(id: 0, name: 'Home')
              else
                Search.find(params.expect(:search_id))
              end
    @subtitle = @search.name
  end

  def set_results
    @results = @search.results.fetch(:things, [])
  end
end