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
|
# File 'lib/greentable/export.rb', line 14
def _call(env)
status, , response = @app.call(env)
greentable_export = (env['QUERY_STRING'] || '').scan(/greentable_export=([csv|print]+)/i)[0][0] rescue nil
if greentable_export
request = Rack::Request.new(env)
greentable_id = request.params['greentable_id']
if greentable_id
body = response.respond_to?(:body) ? response.body : response.join
require 'nokogiri'
doc = Nokogiri(body.to_s)
if greentable_export == 'csv'
ret= ""
(doc/"##{greentable_id} / * / tr").each do |tr|
row = []
col = 0
(tr/"./th | ./td").each do |x|
colspan = x.attributes['colspan']
if colspan
colspan = colspan.value.to_i rescue nil
end
colspan ||= 1
row[col] = (x.inner_text || '').strip
col += colspan
end
CSV.generate(ret, :encoding => 'UTF-8'){ |csv| csv << row }
end
filename = request.params['greentable_export_filename'] || "export"
["Content-Length"] = ret.length.to_s
["Content-Type"] = "text/csv"
["Content-Disposition"] = "attachment; filename=#{filename}.#{greentable_export}"
.delete('ETag')
.delete('Cache-Control')
response = [ret]
elsif greentable_export == 'print'
table_node = doc.css("##{greentable_id}").remove
body = doc.css('body')[0]
js_print = "<script>window.onload = function() { window.focus(); window.print(); }</script>"
body.inner_html = table_node.to_html + js_print
response = [doc.to_html]
end
end
end
[status, , response]
end
|