Module: Sinatra::ReportHandler

Extended by:
Hexacta
Defined in:
lib/sinatra/handlers/reports.rb

Constant Summary

Constants included from Hexacta

Hexacta::GEM_FILE_DIR

Instance Method Summary collapse

Methods included from Hexacta

copy_all_files, copy_dir_structure, copy_file, gem_path, setup_dir

Instance Method Details

#enable_reportsObject



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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/sinatra/handlers/reports.rb', line 6

def enable_reports
  p "Enabling reports..."

  #In order to enable file streaming
  helpers do
    def slim(template, options = {}, locals = {}, &block)
      # Slim calls the option :streaming, but Sinatra has a #stream method
      # so we also support the :stream option.
      options[:streaming] ||= options.delete(:stream)

      # We are not streaming. Call super implementation and
      # just ensure that the @_out_buf is restored afterwards.
      unless options[:streaming]
        old = @_out_buf
        begin
          return super
        ensure
          @_out_buf = old
        end
      end

      # We use the Temple generator without preamble and postamble
      # which is suitable for streaming.
      options[:generator] = Temple::Generator

      # We are already streaming, continue!
      return super if @_out_buf.is_a? Sinatra::Helpers::Stream

      # Create a new stream
      stream do |out|
        @_out_buf = out

        if options[:layout] == false
          # No layout given, start rendering template
          super
        else
          # Layout given
          layout = options[:layout] == nil || options[:layout] == true ? :layout : options[:layout]

          # Invert layout and template rendering order
          super layout, options.merge(layout: false), locals do
            super(template, options.merge(layout: false), locals, &block)
          end
        end
      end
    end
  end

  before '/reports/*' do
    error(403) unless authenticated(User).admin?
  end

  get '/reports' do
    slim :reports
  end

  get '/reports/:report_name' do |report_name|
    begin
      date = Date.parse(params[:date]) unless params[:date].nil?
      date ||= Date.today
      headers "Content-Disposition" => "attachment;filename=#{report_name}.#{date}.xls",
        "Content-Type" => "application/octet-stream"
        slim "reports/#{report_name}".to_sym, locals: { :date => date }, :stream => true, :layout => false
    rescue Exception => e
      NotificationSender.instance.send_error(authenticated(User),e.message,e.backtrace.join('\n'))
      halt 400, e.message
    end
  end
end