Module: HighchartsExporting::Exporter

Defined in:
lib/highcharts_exporting/exporter.rb

Instance Method Summary collapse

Instance Method Details

#exportObject


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
# File 'lib/highcharts_exporting/exporter.rb', line 10

def export
  tmp_dir = Rails.root.join('tmp/highcharts').to_s
  FileUtils.mkdir_p tmp_dir

  @infile_tmp_file = nil
  if params[:options]
    @infile_tmp_file = Tempfile.new(['options', '.json'], tmp_dir)
    temp_write(@infile_tmp_file, params[:options])
  elsif params[:svg]
    @infile_tmp_file = Tempfile.new(['options', '.svg'], tmp_dir)
    temp_write(@infile_tmp_file, params[:svg])
  end


  infile_path = @infile_tmp_file.path
  type = params[:type] || 'image/png'
  extension = MIME::Types[type].first.extensions.first

  @output_tmp_file = Tempfile.new(['output', ".#{extension}"], tmp_dir)
  output_path = @output_tmp_file.path

  @callback_tmp_file = nil
  callback_path = if params[:callback]
                    @callback_tmp_file = Tempfile.new(['callbacks', '.js'], tmp_dir)
                    temp_write(@callback_tmp_file, params[:callback])
                    @callback_tmp_file.path
                  else
                    nil
                  end

  filename = params[:filename] || 'Chart'
  scale = params[:scale] || 2
  width = params[:width]
  constr = params[:constr] || 'Chart'

  convert_args = convert_args({
      infile: infile_path,
      outfile: output_path,
      scale: scale,
      width: width,
      constr: constr,
      callback: callback_path
  })

  result = ::Phantomjs.run(*convert_args)
  puts result if VERBOSE

  # TODO: clean @output_tmp_file
  @infile_tmp_file.delete
  @callback_tmp_file.delete if @callback_tmp_file

  if /Error/ =~ result
    render text: result, status: 500
  else
    send_file output_path, filename: "#{filename}.#{extension}", type: type
  end
end