Last active
September 9, 2015 22:13
-
-
Save latortuga/892788b74fb1f36ec069 to your computer and use it in GitHub Desktop.
CSV Renderer/Helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= 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 %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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