Skip to content

Instantly share code, notes, and snippets.

@Phazz
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Phazz/7eed02f6a2fd4c09269c to your computer and use it in GitHub Desktop.
Save Phazz/7eed02f6a2fd4c09269c to your computer and use it in GitHub Desktop.

I have the following task (removed some code for clarity) app/main/tasks/csv_exporter_tasks.rb

require 'mongo'

class CsvExporterTasks < Volt::Task
  include Mongo

  def run
    db = db_connect
    sku = db.collection('sku')
    headers = sku.find.map {|i| i.keys}.flatten.uniq
    keys = headers.each_with_object({}) {|k, h| h[k] = :asc}
    sorted_collection = sku.find.sort(keys)
    generate_csv_string(sorted_collection, headers) # returning a string
  end
  
  private
  
  def generate_csv_string(collection, headers)
    CSV.generate do |csv|
      csv << headers
      collection.each_slice(10) do |sku_hashes|
        sku_hashes.each do |sku_hash|
          csv << sku_hash.values.to_a
        end
      end
    end
  end
end

I have the following controller app/main/controllers/file_export_controller.rb

module Main
  class FileExportController < Volt::HttpController
    def csv_export
      csv = CsvExporterTasks.run
      csv.then do |file|
        render text: file # How can I stream this file to the browser in Volt? Cannot find any method doing that.
      end
    end

  end
end

I have the following view app/main/views/main/exports.html

<:Title>
  Exports

<:Body>
<form action="/exports/csv" method="post">
<input type="submit" name="export_csv" value="CSV export"></form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment