Last active
August 29, 2015 14:12
-
-
Save gregory/8a1be5864cdf0fb0b3d5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'csv' | |
module Extensions | |
module Csv | |
module ClassMethods | |
# Public: import a csv file | |
# | |
# file_path - the filepath of the csv file | |
# | |
# Yields a hash of the values of the row | |
# | |
# Examples | |
# | |
# CSV.import("/foo.csv") | |
def import(file_path) | |
csv_text = File.read(file_path) | |
CSV.parse(csv_text, headers: true).map(&:to_hash).each do |row| | |
yield(row) | |
end | |
end | |
# Public: Build a csv file out of an array | |
# | |
# collection - (ActiveRelation ||Enumerable) The collection of elements to build the rows | |
# columns - (Hash) the columns's headers and methods to build the rows | |
# meta - (Hash) meta info about the file we want to generate | |
# | |
# Examples | |
# | |
# columns = { | |
# 'Name' => :name, | |
# 'Number of friends' => ->(user) { |user| user.friends.single.sexy.count }, | |
# 'empty line' => nil | |
# } | |
# meta = { filename: 'foo' } | |
# Csv.export(collection, columns, meta) | |
# # => new file in your tmp/exports/csv/foo.csv | |
# | |
# Create a csv file in tmp/exports/csv/ and return the array | |
def export(collection, columns, meta={}) | |
path = File.join(Rails.root, 'private', 'exports', 'csv') | |
fname = "#{meta[:filename]}" if meta[:filename].present? | |
fname ||= "#{meta[:prefix] || ""}#{Date.today.strftime("%m-%d-%Y")}-#{Time.now.to_i}.csv" | |
fmode = meta[:filemode] || 'wb' | |
FileUtils.mkdir_p(path, mode: 0700) | |
filename = File.join(path, fname) | |
CSV.open(filename, fmode) do |csv| | |
if block_given? | |
csv << [*columns].flatten | |
collection.each do |element| | |
yield(csv, element) | |
end | |
else | |
raise 'Expecting columns to be a Hash' unless columns.is_a?(Hash) | |
csv << columns.keys | |
collection.each do |element| | |
csv << columns.values.map do |method| | |
if method.is_a?(Proc) | |
method.call(element) | |
elsif method.is_a?(Symbol) | |
element.send(method) | |
else | |
method | |
end | |
end | |
end | |
end | |
end | |
filename | |
end | |
end | |
end | |
end | |
CSV.send(:extend, Extensions::Csv::ClassMethods) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment