Skip to content

Instantly share code, notes, and snippets.

@latortuga
Last active September 9, 2015 22:13
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 latortuga/892788b74fb1f36ec069 to your computer and use it in GitHub Desktop.
Save latortuga/892788b74fb1f36ec069 to your computer and use it in GitHub Desktop.
CSV Renderer/Helper
<%= CSV.generate do |csv| %>
<% csv << ["All Orders"] %>
<% csv << [] %>
<% total = 0.0 %>
<% orders.each do |order| %>
<% csv << [order.id, order.subtotal, order.tax, order.shipping, order.total] %>
<% total += order.total %>
<% end %>
<% csv << [] %>
<% csv << ["Total", total] %>
<% end %>
class OrderCsvPresenter
include CsvRenderer
attr_accessor :orders
def initialize(orders)
@orders = orders
end
def prepare_csv
csv_row "All Orders"
blank_csv_row
total = 0.0
orders.each do |order|
csv_row [order.id, order.subtotal, order.tax, order.shipping, order.total]
total += order.total
end
blank_csv_row
csv_row ["Total", total]
end
end
module CsvRenderer
def blank_csv_row
_csv_rows << []
end
def prepare_csv
raise NotImplementedError, "Implement #prepare_csv in your class to create actual CSV rows."
end
def csv_row(item)
_csv_rows << Array(item)
end
def to_csv
prepare_csv
CSV.generate do |csv|
_csv_rows.each do |row|
csv << row
end
end
end
private
def _csv_rows
@_csv_rows ||= []
end
end
class OrdersController < ApplicationController
def index
@orders = Order.all
respond_to do |format|
format.csv do
data = OrderCsvPresenter.new(orders: @orders).to_csv
send_data(data, filename: 'orders.csv', type: 'text/csv')
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment