Class: Greentable::Export

Inherits:
Object
  • Object
show all
Defined in:
lib/greentable/export.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, *args, &block) ⇒ Export



5
6
7
8
# File 'lib/greentable/export.rb', line 5

def initialize(app, *args, &block)
  @app = app
  @env = nil
end

Instance Method Details

#_call(env) ⇒ Object



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, headers, 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"
        headers["Content-Length"] = ret.length.to_s
        headers["Content-Type"] = "text/csv"
        headers["Content-Disposition"] = "attachment; filename=#{filename}.#{greentable_export}"
        headers.delete('ETag')
        headers.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, headers, response]
end

#call(env) ⇒ Object



10
11
12
# File 'lib/greentable/export.rb', line 10

def call(env)
  dup._call(env)
end