Method: CustomTableConcern#custom_table_export

Defined in:
app/controllers/concerns/custom_table_concern.rb

#custom_table_export(format, collection, filename: nil) ⇒ Object



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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'app/controllers/concerns/custom_table_concern.rb', line 39

def custom_table_export(format, collection, filename: nil)

  filename ||= collection.model.model_name.plural

  format.xlsx do
    # if collection.count > 1000
      # redirect_to params.permit!.merge({:format => :html}), alert: t("custom_table.huge_xlsx_alert", csv: helpers.link_to(t("custom_table.download_as_csv"), params.permit!.merge({:format => :csv})))
    # else
      response.headers['Content-Disposition'] = "attachment; filename=\"#{filename}.xlsx\""
    # end
  end

  format.csv do
    # Delete this header so that Rack knows to stream the content.
    headers.delete("Content-Length")
    # Do not cache results from this action.
    headers["Cache-Control"] = "no-cache"
    # Let the browser know that this file is a CSV.
    headers['Content-Type'] = 'text/csv'
    # Do not buffer the result when using proxy servers.
    headers['X-Accel-Buffering'] = 'no'
    # Set the filename
    headers['Content-Disposition'] = "attachment; filename=\"#{filename}.csv\"" 

    global_model_name = collection.model.model_name.singular

    fields = helpers.custom_table_fields_definition_for(collection.model)

    # Allow pre-defined fields for export
    if !@fields.nil?
      fields = fields.select { |k, _v| local_assigns[:fields].include?(k) }
    end 

    @csv_enumerator ||= Enumerator.new do |yielder|

      head = []

      fields.each do |field, defs|
        head.push (defs[:label].nil? ? collection.model.human_attribute_name(field) : defs[:label])
      end

      yielder << CSV.generate_line(head)

      collection.find_each do |item|

        row = []
        model_name = item.model_name.singular # Allows to show different class models in one table!
  
        fields.each do |field, defs|
          next if defs[:table] == false
      
          value = helpers.raw_field_value_for(item, field)
      
          if [Date, ActiveSupport::TimeWithZone].include?(value.class)
            value = value.to_date
          end
      
          row.push value
        end
      
        # Extra cols definition
        if defined?(@extra_cols)
          row += @extra_cols.call(item)
        end    

        yielder << CSV.generate_line(row)
      end
    end

    self.response_body = @csv_enumerator
  end

end